//
//  DataSynchronization.m
//  Estate
//
//  Created by heyong on 16/7/27.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "dataInit.h"


#import "DataSynchronization.h"

@interface DataSynchronization ()
{
    dispatch_group_t group;
}

// 数据库
@property (strong , nonatomic)FMDatabase *db;
/**初始化数据对象*/
@property (strong, nonatomic) dataInit *reData;
// 用户表更新数据
@property (strong, nonatomic) NSMutableArray *userArr;
// 记录表更新数据
@property (strong, nonatomic) NSMutableArray *workRecordArr;
// 日记表更新数据
@property (strong, nonatomic) NSMutableArray *workDiaryArr;
// 日志表更新数据
@property (strong, nonatomic) NSMutableArray *workLogArr;
// 单位表更新数据
@property (strong, nonatomic) NSMutableArray *unitArr;
// 项目人员表更新数据
@property (strong, nonatomic) NSMutableArray *proUsers;
// 项目单位表
@property (strong, nonatomic) NSMutableArray *proUnitArr;
// 广告表
@property (strong, nonatomic) NSMutableArray *advArr;
// 配置
@property (strong, nonatomic) NSMutableArray *systemArr;

#pragma mark - 附件表
// 附件表新增数据
@property (strong, nonatomic) NSMutableArray *attachArr;
// 变更的附件
@property(strong, nonatomic)NSMutableArray *addWorkRecordArr;
@property(strong, nonatomic)NSMutableArray *addInspectRecordArr;
// 存储所有新增数据的id 为fileIds。附件表传参使用
@property(strong, nonatomic)NSMutableArray *attachFileids;

// 项目表新增返回id数据;
@property(strong, nonatomic)NSMutableArray *proidsArr;
// 添加本地流程状态数组
@property (strong, nonatomic) NSMutableArray *aProcessArr;
// 删除本地流程状态数组
@property (strong, nonatomic) NSMutableArray *dProcessArr;

#pragma mark - 巡检
//巡检流程更新数据
@property (strong, nonatomic) NSMutableArray *inspectProcessArr;
//巡检流程记录更新数据
@property (strong, nonatomic) NSMutableArray *inspectProcrssRecordArr;
//巡检项实体更新数据
@property (strong, nonatomic) NSMutableArray *inspectItemArr;
//用户巡检项更新数据
@property (strong, nonatomic) NSMutableArray *inspectUserItemArr;
//工程巡检一键汇总更新数据
@property (strong, nonatomic) NSMutableArray *inspectTotalRecordArr;
//巡检组更新数据
@property (strong, nonatomic) NSMutableArray *inspectGroupArr;
//巡检组用户更新数据
@property (strong, nonatomic) NSMutableArray *inspectGroupUserArr;

@end


@implementation DataSynchronization

#pragma mark - 懒加载(初始化数据源)
- (FMDatabase *)db {
    if(_db==nil){
        _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    }
    return _db;
}

- (NSMutableArray *)proidsArr {
    if (!_proidsArr) {
        _proidsArr = [NSMutableArray array];
    }
    return _proidsArr;
}

- (NSMutableArray *)addWorkRecordArr{
    if(!_addWorkRecordArr){
        _addWorkRecordArr=[NSMutableArray array];
    }
    return _addWorkRecordArr;
}

- (NSMutableArray *)addInspectRecordArr{
    if(!_addInspectRecordArr ){
        _addInspectRecordArr=[NSMutableArray array];
    }
    return _addInspectRecordArr;
}

- (dataInit *)reData{
    if(_reData==nil){
        _reData = [[dataInit alloc]init];
    }
    return _reData;
}

- (NSMutableArray *)userArr {
    if(_userArr==nil){
        _userArr=[NSMutableArray array];
    }
    return _userArr;
}

- (NSMutableArray *)workRecordArr {
    if(_workRecordArr==nil){
        _workRecordArr=[NSMutableArray array];
    }
    return _workRecordArr;
}

- (NSMutableArray *)workDiaryArr {
    if(!_workDiaryArr){
        _workDiaryArr=[NSMutableArray array];
    }
    return _workDiaryArr;
}

- (NSMutableArray *)attachArr {
    if(!_attachArr){
        _attachArr=[NSMutableArray array];
    }
    return _attachArr;
}

- (NSMutableArray *)workLogArr {
    if(!_workLogArr){
        _workLogArr=[NSMutableArray array];
    }
    return _workLogArr;
}

- (NSMutableArray *)unitArr {
    if(!_unitArr){
        _unitArr=[NSMutableArray array];
    }
    return _unitArr;
}

- (NSMutableArray *)proUnitArr {
    if(!_proUnitArr){
        _proUnitArr=[NSMutableArray array];
    }
    return _proUnitArr;
}

- (NSMutableArray *)proUsers {
    if(_proUsers==nil){
        _proUsers=[NSMutableArray array];
    }
    return _proUsers;
}

- (NSMutableArray *)inspectProcessArr {
    if(!_inspectProcessArr){
        _inspectProcessArr=[NSMutableArray array];
    }
    return _inspectProcessArr;
}

- (NSMutableArray *)inspectProcrssRecordArr {
    if(!_inspectProcrssRecordArr){
        _inspectProcrssRecordArr=[NSMutableArray array];
    }
    return _inspectProcrssRecordArr;
}

-(NSMutableArray *)inspectItemArr {
    if(!_inspectItemArr){
        _inspectItemArr=[NSMutableArray array];
    }
    return _inspectItemArr;
}

- (NSMutableArray *)inspectUserItemArr{
    if(!_inspectUserItemArr){
        _inspectUserItemArr=[NSMutableArray array];
    }
    return _inspectUserItemArr;
}

- (NSMutableArray *)inspectTotalRecordArr {
    if(!_inspectTotalRecordArr){
        _inspectTotalRecordArr=[NSMutableArray array];
    }
    return _inspectTotalRecordArr;
}

-(NSMutableArray *)inspectGroupArr {
    if(!_inspectGroupArr){
        _inspectGroupArr=[NSMutableArray array];
    }
    return _inspectGroupArr;
}

- (NSMutableArray *)inspectGroupUserArr {
    if(!_inspectGroupUserArr){
        _inspectGroupUserArr=[NSMutableArray array];
    }
    return _inspectGroupUserArr;
}

- (NSMutableArray *)advArr {
    if(!_advArr){
        _advArr=[NSMutableArray array];
    }
    return _advArr;
}

- (NSMutableArray *)systemArr {
    if(!_systemArr){
        _systemArr=[NSMutableArray array];
    }
    return _systemArr;
}

- (NSMutableArray *)attachFileids {
    if(!_attachFileids){
        _attachFileids=[NSMutableArray array];
    }
    return _attachFileids;
}

// 添加本地流程数组
- (NSMutableArray *)aProcessArr {
    if (!_aProcessArr) {
        _aProcessArr = [NSMutableArray array];
    }
    return _aProcessArr;
}

// 删除本地流程状态数组
- (NSMutableArray *)dProcessArr {
    if (!_dProcessArr) {
        _dProcessArr = [NSMutableArray array];
    }
    return _dProcessArr;
}


#pragma mark - 数据同步方法集

/*
 * 触发同步调用的方法
 * refresh 是否刷新
 * isNet 是否有网
 */
- (void) syncDataFromTable :(UIView *)view refresh:(BOOL)refresh isNet:(BOOL)isNet andExit:(BOOL)exit {
 
    if (!isNet) {
        
        [LSUtility showToastWithMessage:@"请连接网络！" inView:view Andtime:2.5];
        
    } else {
        group = dispatch_group_create();
        UIWindow *myWindow = [UIApplication sharedApplication].keyWindow;
        UIView *views = [[UIView alloc]initWithFrame:myWindow.bounds];
        views.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.1];
        [myWindow addSubview:views];
        [LSUtility showMBProgress:views message:@"数据同步中..."];
        
        // 用户
        [self downloadUser];
        // 记录表
        [self uploadWorkRecord];
        // 日记表
        [self uploadworkDiary];
        // 日志表
        [self uploadworkLog];
        // 附件上传
        [self uploadAttachment];
        // 广告表
        [self downLoadAdv];
        // 配置表
        [self downSystemConfig];
        // 查询项目单位的地址
        [self downloadProUnit];
        
        // 巡检流程表 先同步流程在同步其它相关联的
        [self uploadInspectProcess];
        // 巡检项
        [self downloadInspectItem];
        // 上传巡检流程记录表
        [self uploadInspectProcessRecord];
        [self downloadInspectProcessRecord];
        // 用户巡检项
        [self uploadInspectUserItem];
        [self downloadInspectUserItem];
        // 一键汇总
        [self uploadInspectTotalRecord];
        [self downloadInspectTotalRecord];
        // 巡检组
        [self downloadInspectGroup];
        // 巡检组用户
        [self downloadInspectGroupUser];
        // 流程表
        [self uploadProces];
        // 流程记录表
        [self uploadProcessRecord];
        
        // 见证取样流程表
        [self uploadSamplesProcess];
        // 见证取样流程记录表
        [self uploadSampleProcessRecord];
        
        // 项目表
        [self downloadProject];
        // 项目概览表
        [self downloadProjectProfile];
        // 同步巡视表
        [self localPatrolUpdateServer];
        // 同步安全基本表
        [self localSafeBasicUpdateServer];
        // 同步安全施工三类人员
        [self localSafeConstructUpdateServer];
        // 同步安全特种作业人员
        [self localSafeSpecialTypeUpdateServer];
        // 同步监理安全巡查
        [self localSecurityPatrolUpdateServer];
        // 同步危险性较大工程监理检查
        [self localSafeDangerUpdateServer];
        // 同步施工设备进场
        [self localSafeDeviceUpdateServer];
     
        // 查询服务器附件表
        dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
          
            [self downloadAttachmentFromServer:views isLoad:YES andExit:exit];
            NSDictionary *advDic1 = [LSUtility queryAdvAttachment:@"1332d771-aea5-42ca-a995-2f0cfd57320c"];
            if (advDic1) {
                NSLog(@"有附件");
            }else{
                NSLog(@"没有附件");
            }
            // 刷新数据
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if (refresh) {
                    NSDictionary *advDic = [LSUtility queryAdvAttachment:@"1332d771-aea5-42ca-a995-2f0cfd57320c"];
                    if (advDic) {
                        NSLog(@"有附件");
                    }else{
                        NSLog(@"没有附件");
                    }
                    //天气 同步按钮
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"weatherRe" object:nil];
                    // 通知首页刷新数据
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"home" object:nil];
                    //广告
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshAdv" object:nil];
                    //见证取样
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:nil];
                    //工程巡检
                    NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjrw" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter]postNotification:notice];
                }
            });
        });
    }
    
}

#pragma mark - 同步用户表
- (void)downloadUser {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr = [self getIdAndModifyTimeFromTable:USER];
    if (arr!=nil) {
        //本地数组转换成json
        NSString *json=[LSUtility dictionaryToJson:arr];
        [dic setObject:json forKey:@"localdata"];
    } else {
        [dic setObject:@"" forKey:@"localdata"];
    }
    [LSHttpTool Post:URL_USER_SELECT parameters:dic success:^(id responseObject) {
        
        NSString *code=[responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [self.userArr addObject:mDict];
            }
            //执行本地数据更改方法
            [self updateUser];
            
        } else {
            NSLog(@"人员查询错误2499：%@",responseObject);
        }
    } failure:^(NSError *error) {
        
    }];
}

// 更新本地用户表
- (void)updateUser {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    
    if (self.userArr.count > 0) {
        for (NSMutableDictionary  *workdic in self.userArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:workdic[@"id"]];
                //修改或新增本地数据
            } else {
                [upArr addObject:workdic];
            }
        }
        // 删除方法
        if(deleteIdArr.count>0){
            [LSUtility deleteTable:USER andIdArr:deleteIdArr];
        }
        // 新增 更改方法
        if(upArr.count>0){
            [self.reData saveUser:upArr];
        }
    } else{
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 工作记录表同步
- (void)uploadWorkRecord {
    //本地新增或者修改的数据
    NSMutableArray *workRecordArr = [self queryLocalModifyModAndAddIDForTable:WORK_RECORD];
    
    if (workRecordArr.count>0) {
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:workRecordArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_WORKRECORD_INSERT parameters:dic  success:^(id responseObject) {
            
            //            NSLog(@"记录：%@\nmsg:%@",responseObject,responseObject[@"msg"]);
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                DeLog(@"本地记录无数据更新成功");
                //修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
#
                    [self updateStateForTable:WORK_RECORD andId:dic[@"id"]];
                }
                
                // 查询服务器数据
                [self downloadWorkRecord];
                NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter]postNotification:notice];
                NSNotification * notice1 = [NSNotification notificationWithName:@"Refresh_jl_jl" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter]postNotification:notice1];
                NSNotification * notice2 = [NSNotification notificationWithName:@"Refresh_zj_jl" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter]postNotification:notice2];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                //查询服务器数据
                [self downloadWorkRecord];
            }
        } failure:^(NSError *error) {
            //查询服务器数据
            [self downloadWorkRecord];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        //查询服务器数据
        [self downloadWorkRecord];
    }
}

// 查询服务器工作记录, 更新本地数据
- (void)downloadWorkRecord {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSArray *arr = [self getIdAndModifyTimeFromTable:WORK_RECORD];
    if (arr!=nil) {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
        NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
        if (role&&role.length>0) {
            [dic setObject:role forKey:@"userType"];
        }
        dispatch_group_enter(group);
        
        // 更新数据请求
        [LSHttpTool Post:URL_WORKRECORD_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.workRecordArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateWork];
                
            } else {
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    } else {
        dispatch_group_enter(group);
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [dic setObject:[self parameterDownLoadWorkLogProIds] forKey:@"proIds"];
        NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
        if (role&&role.length>0) {
            [dic setObject:role forKey:@"userType"];
        }
        // 更新数据请求
        [LSHttpTool Post:URL_WORKRECORD_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code = [responseObject objectForKey:@"code"];
            if ([code isEqualToString:@"1"]) {
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.workRecordArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateWork];
                
            } else {
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    }
}

// 工作记录本地插入 删除。
-(void)updateWork {
    // 需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    // 是否存在更改的值
    if(self.workRecordArr.count > 0) {
        
        for (NSMutableDictionary  *workdic in self.workRecordArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:workdic[@"id"]];
                
                // 修改或新增本地数据
            } else {
                [self.addWorkRecordArr addObject:workdic];
            }
        }
        
        // 删除方法
        if(deleteIdArr.count>0){
            [LSUtility deleteTable:WORK_RECORD andIdArr:deleteIdArr];
        }
        
        // 新增 更改方法
        if (self.addWorkRecordArr.count>0) {
            [self.reData saveWorkRecord:self.addWorkRecordArr];
            //附件下载
            for (NSDictionary *dic in self.addWorkRecordArr) {
                [self.attachFileids addObject:dic[@"id"]];
            }
        }
        
        if (deleteIdArr.count>0||self.addWorkRecordArr.count>0) {
            NSNotification * notice1= [NSNotification notificationWithName:@"Refresh_jl_jl" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice1];
            NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice];
            NSNotification * notice3 = [NSNotification notificationWithName:@"Refresh_zj_jl" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice3];
            NSNotification * notice4 = [NSNotification notificationWithName:@"indexView" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice4];
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma  mark - 日记表

// 日记表同步
- (void)uploadworkDiary {
    
    // 本地新增或者修改的数据
    NSMutableArray *workDiaryArr=[self queryLocalModifyModAndAddIDForTable:WORK_DIARY];
    if (workDiaryArr.count > 0) {
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:workDiaryArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_WORKDIARY_INSERT parameters:dic  success:^(id responseObject) {
            
            if([[responseObject objectForKey:@"code"]isEqualToString:@"1"]){
                // 修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:WORK_DIARY andId:dic[@"id"]];
                }
                // 查询服务器数据
                [self downloadWorkDiary];
                NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_rj" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter]postNotification:notice];
                NSNotification * notice1 = [NSNotification notificationWithName:@"Refresh_zj_rj" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter]postNotification:notice1];
                
            } else {
                NSLog(@"本地日记数据更新失败");
            }
        } failure:^(NSError *error) {
            // 查询服务器数据
            [self downloadWorkDiary];
            
        }];
    } else {
        // 查询服务器数据
        [self downloadWorkDiary];
    }
}

// 查询服务器数据同步到本地(日记表)
- (void)downloadWorkDiary {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr = [self getIdAndModifyTimeFromTable:WORK_DIARY];
    dispatch_group_enter(group);
    if (arr != nil) {
        
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
        NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
        if (role&&role.length>0) {
            [dic setObject:role forKey:@"userType"];
        }
        // 更新数据请求
        [LSHttpTool Post:URL_WORKDIARY_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            if ([code isEqualToString:@"1"]) {
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.workDiaryArr addObject:mDict];
                    [self.attachFileids addObject:mDict[@"id"]];
                }
                //执行本地数据更改方法
                [self updateWorkDiary];
                
            } else {
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
        }];
        
    } else {
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [dic setObject:[self parameterDownLoadWorkLogProIds] forKey:@"proIds"];
        NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
        if (role&&role.length>0) {
            [dic setObject:role forKey:@"userType"];
        }

        //更新数据请求
        [LSHttpTool Post:URL_WORKDIARY_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            NSLog(@"responseObject:%@",[responseObject objectForKey:@"data"]);
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.workDiaryArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateWorkDiary];
                
            } else {
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            
        }];
    }
}

// 更新本地日记表
- (void)updateWorkDiary {
    // 需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    // 需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    // 是否存在更改的值
    if (self.workDiaryArr.count > 0) {
        for (NSMutableDictionary  *workdic in self.workDiaryArr) {
            //删除本地数据
            if([[workdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:workdic[@"id"]];
                
                // 修改或新增本地数据
            } else {
                [upArr addObject:workdic];
            }
        }
        
        // 删除方法
        if (deleteIdArr.count>0) {
            [LSUtility deleteTable:WORK_DIARY andIdArr:deleteIdArr];
        }
        
        // 新增 更改方法
        if (upArr.count>0) {
            [self.reData saveDiary:upArr];
        }
        
        if (deleteIdArr.count>0 || upArr.count>0) {
            NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_rj" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice];
            NSNotification * notice1 = [NSNotification notificationWithName:@"Refresh_zj_rj" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice1];
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma  mark - 日志表

// 本地日志表同步
- (void)uploadworkLog {
    //本地新增或者修改的数据
    NSMutableArray *workLogArr = [self queryLocalModifyModAndAddIDForTable:WORK_LOG];
    if (workLogArr.count > 0) {
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:workLogArr];
        [dic setValue:json forKey:@"list"];
        //        DeLog(@"日志入参：%@",dic);
        [LSHttpTool Post:URL_WORKLOG_INSERT parameters:dic success:^(id responseObject) {
            
            //            NSLog(@"responseObject:%@",responseObject);
            if([[responseObject objectForKey:@"code"]isEqualToString:@"1"]){
                //修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:WORK_LOG andId:dic[@"id"]];
                }
                //下载数据
                [self downloadWorkLog];
                NSLog(@"本地日志上行成功");
                
            } else {
                NSLog(@"本地日志上行失败");
            }
        } failure:^(NSError *error) {
            NSLog(@"本地日志上行失败");
            [self downloadWorkLog];
        }];
    } else {
        NSLog(@"日志无审核操作");
        [self downloadWorkLog];
    }
}

// 查询服务器日志表数据，下载到本地。(下载操作)
- (void)downloadWorkLog {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[self getIdAndModifyTimeFromTable:WORK_LOG];
    dispatch_group_enter(group);
    if (arr!=nil) {
        
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
        [dic setObject:[self parameterDownLoadWorkLogProIds] forKey:@"proIds"];
        if(![dic[@"proIds"] isEqualToString:@""]){
            //更新数据请求
            [LSHttpTool Post:URL_WORKLOG_SELECT parameters:dic success:^(id responseObject) {
                
                NSLog(@"日志表数据返回：%@",responseObject);
                NSString *code=[responseObject objectForKey:@"code"];
                if ([code isEqualToString:@"1"]) {
                    NSLog(@"日志%@",responseObject[@"data"]);
                    for (NSDictionary *mudic in responseObject[@"data"]) {
                        //得到服务器返回的字典
                        NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                        [self.workLogArr addObject:mDict];
                    }
                    //执行本地数据更改方法
                    [self updateWorkLog];
                    
                } else {
                    NSLog(@"错误721-%@",[responseObject objectForKey:@"msg"]);
                }
                dispatch_group_leave(group);
                
            } failure:^(NSError *error) {
                dispatch_group_leave(group);
            }];
        } else {
            NSLog(@"日志同步巡检不存在项目ID");
            dispatch_group_leave(group);
        }
    } else {
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [dic setObject:[self parameterDownLoadWorkLogProIds] forKey:@"proIds"];
        DeLog(@"入参：%@",dic);
        //更新数据请求
        [LSHttpTool Post:URL_WORKLOG_SELECT parameters:dic success:^(id responseObject) {
            NSString *code=[responseObject objectForKey:@"code"];
            // NSLog(@"responseObject:%@",[responseObject objectForKey:@"data"]);
            NSLog(@"日志表数据返回：%@",responseObject);
            
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.workLogArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateWorkLog];
            }else{
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            
        }];
    }
}

// 下行日志到本地 入参2
- (NSMutableString *)parameterDownLoadWorkLogProIds {
    NSMutableArray *logArr=[LSUtility queryProsByUserId:USERID];
    logArr = [logArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSString *logJson=[LSUtility dictionaryToJson_2:logArr];
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:logJson];
    
    NSRange range1 = {0,logJson.length};
    [mutStr replaceOccurrencesOfString:@"\""
                            withString:@"'"
                               options:NSLiteralSearch range:range1];
    
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"["
                            withString:@""
                               options:NSLiteralSearch range:range2];
    
    NSRange range3 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"]"
                            withString:@""
                               options:NSLiteralSearch range:range3];
    return mutStr;
}

// 更新本地日志
- (void)updateWorkLog {
    
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.workLogArr.count > 0) {
        
        NSLog(@"返回日志数据:%li条",self.workLogArr.count);
        for (NSMutableDictionary  *workdic in self.workLogArr) {
            // NSLog(@"返回；%@",workdic);
            //删除本地数据
            if([[workdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:workdic[@"id"]];
                
            } else {
                //修改或新增本地数据
                [upArr addObject:workdic];
            }
        }
        
        // 删除方法
        if(deleteIdArr.count>0){
            [LSUtility deleteTable:WORK_LOG andIdArr:deleteIdArr];
        }
        
        // 新增 更改方法
        if(self.workLogArr.count>0){
            [self.reData saveWorkLog:upArr];
            
            // 日志添加附件
            for (NSDictionary *dic in upArr) {
                [self.attachFileids addObject:dic[@"id"]];
            }
        }
        
        if(deleteIdArr.count>0||upArr.count>0){
            NSNotification * notice = [NSNotification notificationWithName:@"Refresh_zj_rz" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice];
        }
    }else{
        NSLog(@"日志无数据更新");
    }
}


#pragma mark - 附件上传
- (void)uploadAttachment {
    
    NSArray *fileArr= [self queryLocalModifyStateIDForTable:ATTACHMENT andState:@"ADD"];
    if (fileArr.count > 0) {
        for (NSString *fileId in fileArr) {
            dispatch_group_enter(group);
            
            NSMutableDictionary *fileDic=[LSUtility queryAttachment:fileId];
            // 传入服务器参数
            NSDictionary *dic=@{
                                @"id":fileDic[@"ID"],
                                @"fileid":fileDic[@"FILE_ID"],
                                @"fileTypeId":fileDic[@"FILE_TYPE_ID"],
                                @"proId":fileDic[@"PRO_ID"],
                                @"fileDesc":fileDic[@"FILE_DESC"],
                                @"extendInfo":fileDic[@"EXTEND_INFO"],
                                @"createtime":fileDic[@"CREATE_TIME"],
                                @"createusername":fileDic[@"CREATE_USER_NAME"],
                                @"syncState":@"-1"
                                };
            
            NSMutableDictionary *parameter=[NSMutableDictionary dictionaryWithDictionary:dic];
            [LSHttpTool upload:URL_UPLOAD parameters:parameter andFileName:fileDic[@"FILE_NAME"] progress:^(id uploadProgress) {
                NSProgress *pro=(NSProgress *)uploadProgress;
                
                DeLog(@"进度：%lf",1.0 *pro.completedUnitCount / pro.totalUnitCount);
                
            } success:^(id success) {
                dispatch_group_leave(group);
                
                DeLog(@"附件服务器返回：%@\nmsg:%@",success,success[@"msg"]);
                NSString *code=success[@"code"];
                if([code isEqualToString:@"1"]){
                    //成功 修改附件状态
                    [self updateStateForTable:ATTACHMENT andId:fileId];
                    
                }else{
                    NSLog(@"上传附件出现错误:%@",success[@"msg"]);
                }
            } failure:^(NSError *error) {
                dispatch_group_leave(group);
            }];
        }
    }else{
        NSLog(@"本地无新增附件");
    }
    
    //附件编辑
    NSArray *upFileArr= [self queryLocalModifyStateIDForTable:ATTACHMENT andState:@"MOD"];
    if(upFileArr.count>0){
        for (NSString *fileId in upFileArr) {
            
            NSMutableDictionary *fileDic=[LSUtility queryAttachment:fileId];
            //传入服务器参数
            NSDictionary *dic=@{
                                @"id":fileDic[@"ID"],
                                @"fileid":fileDic[@"FILE_ID"],
                                @"fileTypeId":fileDic[@"FILE_TYPE_ID"],
                                @"proId":fileDic[@"PRO_ID"],
                                @"fileDesc":fileDic[@"FILE_DESC"],
                                @"extendInfo":fileDic[@"EXTEND_INFO"],
                                @"createtime":fileDic[@"CREATE_TIME"],
                                @"createusername":fileDic[@"CREATE_USER_NAME"],
                                @"syncState":@"-1"
                                };
            NSMutableDictionary *parameter=[NSMutableDictionary dictionaryWithDictionary:dic];
            [LSHttpTool upload:URL_UPLOAD parameters:parameter andFileName:fileDic[@"FILE_NAME"] progress:^(id uploadProgress) {
                
                NSProgress *pro=(NSProgress *)uploadProgress;
                NSLog(@"%lf",1.0 *pro.completedUnitCount / pro.totalUnitCount);
            } success:^(id success) {
                //成功 修改附件状态
                [self updateStateForTable:ATTACHMENT andId:fileId];
                
            } failure:^(NSError *error) {
                
            }];
        }
    }else{
        NSLog(@"本地无新增附件");
    }
}

// 查找本地附件有变更数据ID
- (NSMutableArray *)queryLocalModifyStateIDForTable:(NSString *)table andState:(NSString *)state {
    
    DBHelper *helper = [DBHelper help];
    NSArray *dataArr = [helper DataBase:self.db selectKeyTypes:@{@"ID":@"text"} fromTable:table whereCondition:@{@"LOCAL_MODIFY_STATE":state}];
    //id存入数组
    NSMutableArray *idArray=[NSMutableArray array];
    if(dataArr.count>0){
        for (NSDictionary *dic in dataArr) {
            [idArray addObject:[dic objectForKey:@"ID"]];
        }
    }
    return idArray;
}


#pragma mark - 广告表
- (void)downLoadAdv {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr = [self getIdAndModifyTimeFromTable:ADVERTISING_PICTURE];
    dispatch_group_enter(group);
    if (arr!=nil) {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
        //更新数据请求
        NSLog(@"广告表 入参：%@",dic);
        NSLog(@"%@",URL_ADVERTIING_SELECT);
        [LSHttpTool Post:URL_ADVERTIING_SELECT parameters:dic success:^(id responseObject) {
            
            NSLog(@"广告表返回:%@",responseObject);
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.advArr addObject:mDict];
                }
                //执行本地数据更改方法
                if(self.advArr.count>0){
                 [self updateAdvTable:self.advArr];
                }
                
            } else {
                NSLog(@"广告表错误 945：%@",responseObject );
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            
        }];
    }
    else
    {
        [dic setObject:@"" forKey:@"localdata"];
        //更新数据请求
        [LSHttpTool Post:URL_ADVERTIING_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            //            NSLog(@"responseObject:%@",[responseObject objectForKey:@"data"]);
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.advArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateAdvTable:self.advArr];
                
            } else {
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    }
}

// 更新本地广告表
- (void)updateAdvTable:(NSMutableArray *)arr {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    
    // 是否存在更改的值
    if (arr.count > 0) {
        for (NSMutableDictionary  *advDic in arr) {
            //删除本地数据
            if([[advDic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:advDic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:advDic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:ADVERTISING_PICTURE andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveAdvertisement:upArr];
            
            //附件id记录
            for (NSDictionary *dic in upArr) {
                [self.attachFileids addObject:dic[@"id"]];
            }
        }
        //        //下载附件
        //        [self advDownloadAttachment];
        if(deleteIdArr.count>0||upArr.count>0){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSNotification * notice = [NSNotification notificationWithName:@"refreshAdv" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter]postNotification:notice];
            });
        }
    }else{
        NSLog(@"广告无数据更新");
    }
}


#pragma mark - 配置表
- (void)downSystemConfig {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[self getIdAndModifyTimeFromTable:SYSTEM_CONFIG];
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
        //更新数据请求
        [LSHttpTool Post:URL_SYSTEMCONFIG_SELECT parameters:dic success:^(id responseObject) {
            
            DeLog(@"配置responseObject:%@",responseObject[@"msg"]);
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.systemArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateSystemConfig:self.systemArr];
                
            }else{
                DeLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
        } failure:^(NSError *error) {
            
        }];
    }
    else
    {
        [dic setObject:@"" forKey:@"localdata"];
        //更新数据请求
        [LSHttpTool Post:URL_SYSTEMCONFIG_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            //NSLog(@"responseObject:%@",[responseObject objectForKey:@"data"]);
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.systemArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateSystemConfig:self.systemArr];
                
            } else {
                DeLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
        } failure:^(NSError *error) {
            
        }];
    }
}

// 更新本地配置表数据
- (void)updateSystemConfig:(NSMutableArray *)arr {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    
    //是否存在更改的值
    if (arr.count > 0) {
        for (NSMutableDictionary  *advDic in arr) {
            //删除本地数据
            if([[advDic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:advDic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:advDic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:SYSTEM_CONFIG andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveSystemConfigArray:upArr];
        }
        
        if(deleteIdArr.count>0||upArr.count>0){
            NSNotification * notice = [NSNotification notificationWithName:@"refreshAdv" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice];
        }
    } else {
        NSLog(@"配置无数据更新");
    }
    [LSUtility pushNotification];
    
}


#pragma mark - 项目单位表

// 查询项目单位
- (void)downloadProUnit {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[LSUtility queryUnitNumByProId:USERID andType:@"unitCnt"];
    if (arr!=nil) {
        // 本地数组转换成json
        NSString *json=[LSUtility dictionaryToJson:arr];
        [dic setObject:json  forKey:@"localdata"];
        [LSHttpTool Post:URL_PROJECTUNIT_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.proUnitArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updataProUnit];
                
            } else {
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
        } failure:^(NSError *error) {
            
        }];
    } else {
        
        [dic setObject:@"" forKey:@"localdata"];
        [LSHttpTool Post:URL_PROJECTUNIT_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.proUnitArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updataProUnit];
                
            } else {
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
        } failure:^(NSError *error) {
            
        }];
    }
}

// 更新本地项目单位表
- (void)updataProUnit {
    
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.proUnitArr.count > 0) {
        for (NSMutableDictionary  *workdic in self.proUnitArr) {
            //删除本地数据
            if([[workdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:workdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:workdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:PROJECT_UNIT andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //清空本地数据表
            //            DBHelper *helper=[DBHelper help];
            //            [helper clearDatabase:self.db  from:PROJECT_UNIT];
            //新增 更改方法
            [self.reData saveProUnits:upArr];
        }
    }else{
        NSLog(@"单位无数据更新");
    }
}


#pragma mark - 巡检流程表(更新)
- (void)uploadInspectProcess {
    NSMutableArray *inspectRecordArr=[self queryLocalModifyModAndAddIDForTable:INSPECT_PROCESS];
    if(inspectRecordArr.count>0){
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:inspectRecordArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_INSPECTPROCESS_MODIFY parameters:dic success:^(id responseObject){
            
            if([[responseObject objectForKey:@"code"]isEqualToString:@"1"]){
                //修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:INSPECT_PROCESS andId:dic[@"id"]];
                }
                //下行巡检流程
                [self downloadInspectProcess];
                DeLog(@"上传巡检流程成功");
                
            }else{
                DeLog(@"上传巡检流程失败");
                //下行巡检流程
                [self downloadInspectProcess];
            }
        } failure:^(NSError *error) {
            //下行巡检流程
            [self downloadInspectProcess];
        }];
    }else{
        NSLog(@"巡检流程无数据上传");
        //下行巡检流程
        [self downloadInspectProcess];
    }
}

// 查询巡检流程表，下载到本地。(下载操作)
- (void)downloadInspectProcess {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    //本地非add mod数据
    NSMutableArray *arr=[self getIdAndModifyTimeFromTable:INSPECT_PROCESS];
    dispatch_group_enter(group);
    
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr  forKey:@"localdata"];
        //更新数据请求
        [LSHttpTool Post:URL_INSPECTPROCESS_SELECT parameters:dic success:^(id responseObject) {
            
            NSLog(@"巡检流程记录出参:%@",responseObject);
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.inspectProcessArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateInspectProcess];
                
            }else{
                NSLog(@"巡检流程查询错误-1082：%@",responseObject);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            NSLog(@"巡检流程查询请求发生错误");
        }];
    }
    else
    {
        [dic setObject:@"" forKey:@"localdata"];
        //更新数据请求
        [LSHttpTool Post:URL_INSPECTPROCESS_SELECT parameters:dic success:^(id responseObject) {
            
            DeLog(@"服务器流程出参:%@",responseObject);
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.inspectProcessArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateInspectProcess];
                
            }else{
                DeLog(@"错误-1113：%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            
            NSLog(@"巡检流程查询请求发生错误");
        }];
    }
}

// 本地数据更新(巡检流程表)
-(void)updateInspectProcess {
    // 需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    // 是否存在更改的值
    if (self.inspectProcessArr.count > 0) {
        for (NSMutableDictionary  *inspectdic in self.inspectProcessArr){
            //删除本地数据
            if([[inspectdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:inspectdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [self.addInspectRecordArr addObject:inspectdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:INSPECT_PROCESS andIdArr:deleteIdArr];
        }
        
        if(self.addInspectRecordArr.count>0){
            //新增 更改方法
            [self.reData saveInspectProcess:self.addInspectRecordArr];
            // 再走一遍
            // 巡检流程记录表
            [self uploadInspectProcessRecord];
            [self downloadInspectProcessRecord];
            //  用户巡检项
            [self uploadInspectUserItem];
            [self downloadInspectUserItem];
            //  一键汇总
            [self uploadInspectTotalRecord];
            [self downloadInspectTotalRecord];
            //   巡检组
            [self downloadInspectGroup];
            // 巡检组用户
            [self downloadInspectGroupUser];
        }
        
        if(deleteIdArr.count>0||self.addInspectRecordArr.count>0){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjrw" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter]postNotification:notice];
            });
        }
    }else{
        NSLog(@"巡检流程无数据更新");
    }
}


#pragma mark - 巡检流程记录表

// 上传巡检流程
- (void)uploadInspectProcessRecord {
    
    NSMutableArray *inspectRecordArr=[self queryLocalModifyModAndAddIDForTable:INSPECT_PROCESS_RECORD];
    if(inspectRecordArr.count>0){
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_2:inspectRecordArr];
        [dic setValue:json forKey:@"list"];
        DeLog(@"巡检流程记录入参：%@",dic);
        [LSHttpTool Post:URL_INSPECTPROCESSRECORD_INSERT parameters:dic  success:^(id responseObject) {
            
            if([[responseObject objectForKey:@"code"]isEqualToString:@"1"]){
                DeLog(@"巡检记录上传成功%@",responseObject[@"msg"]);
                //修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:INSPECT_PROCESS_RECORD andId:dic[@"id"]];
                }
            }else{
                DeLog(@"巡检记录上传失败%@",responseObject[@"msg"]);
            }
        } failure:^(NSError *error) {
            
        }];
    }else{
        NSLog(@"巡检记录无数据上传");
    }
}

// 查询巡检流程记录表，下载到本地。(下载操作)
- (void)downloadInspectProcessRecord {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    //本地非add mod数据
    NSMutableArray *arr = [self getIdAndModifyTimeFromTable:INSPECT_PROCESS_RECORD];
    dispatch_group_enter(group);
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
        NSString *str=[self queryInspectProcessIds];
        NSString *inspectProcessIds = [LSUtility strbydan:str];
        if (inspectProcessIds && inspectProcessIds.length>0) {
            [dic setObject:inspectProcessIds forKey:@"inspectProcessIds"];
        }else{
            dispatch_group_leave(group);

            return ;
        }
        //更新数据请求
        [LSHttpTool Post:URL_INSPECTPROCESSRECORD_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            //NSLog(@"记录返回：%@",responseObject);
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.inspectProcrssRecordArr addObject:mDict];
                }
                //NSLog(@"记录返回条数：%li",self.inspectProcrssRecordArr.count);
                //执行本地数据更改方法
                [self updateInspectProcessRecord];
                
            }else{
                NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            NSLog(@"巡检流程记录查询请求发生错误");
            dispatch_group_leave(group);
        }];
    }
    else
    {
        [dic setObject:@"" forKey:@"localdata"];
        // 本地数组转换成json
        NSString *str=[self queryInspectProcessIds];
        NSString *inspectProcessIds = [LSUtility strbydan:str];
        if (inspectProcessIds && inspectProcessIds.length>0) {
            [dic setObject:inspectProcessIds forKey:@"inspectProcessIds"];
        }else{
            dispatch_group_leave(group);

            return ;
        }        //更新数据请求
        [LSHttpTool Post:URL_INSPECTPROCESSRECORD_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            // NSLog(@"记录返回：%@",responseObject);
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.inspectProcrssRecordArr addObject:mDict];
                }
                //                NSLog(@"记录返回条数：%li",self.inspectProcrssRecordArr.count);
                //执行本地数据更改方法
                [self updateInspectProcessRecord];
                
            }else{
                NSLog(@"错误1301-%@",[responseObject objectForKey:@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            NSLog(@"巡检流程记录查询请求发生错误");
        }];
    }
}

// 本地数据更新(巡检流程记录表)
- (void)updateInspectProcessRecord {
    // 需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    // 需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    // 是否存在更改的值
    if (self.inspectProcrssRecordArr.count>0) {
        for (NSMutableDictionary  *inspectdic in self.inspectProcrssRecordArr) {
            //删除本地数据
            if([[inspectdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:inspectdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:inspectdic];
            }
        }
        
        NSLog(@"服务器返回本地需要删除的recordID:%@",deleteIdArr);
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:INSPECT_PROCESS_RECORD andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveInspectProcessRecord:upArr];
            for (NSDictionary *dic in upArr) {
                [self.attachFileids addObject:dic[@"id"]];
            }
        }
        
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjzz" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
    }else{
        NSLog(@"巡检流程记录无数据更新");
    }
}


#pragma mark - 巡检项实体表

// 查询巡检项实体表，更新到本地
- (void)downloadInspectItem {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    //本地非add mod数据
    NSMutableArray *arr=[self getIdAndModifyTimeFromTable:INSPECT_ITEM];
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr  forKey:@"localdata"];
        
    }else{
        [dic setObject:@"" forKey:@"localdata"];
    }
    
    //更新数据请求
    [LSHttpTool Post:URL_INSPECTITEM_SELECT parameters:dic success:^(id responseObject) {
        NSString *code=[responseObject objectForKey:@"code"];
        if([code isEqualToString:@"1"]){
            
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [self.inspectItemArr addObject:mDict];
            }
            //执行本地数据更改方法
            [self updateInspectItem];
        }else{
            NSLog(@"错误1467-%@",[responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        
    }];
}

// 本地数据更新(巡检项表)
-(void)updateInspectItem {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.inspectItemArr.count > 0) {
        for (NSMutableDictionary  *inspectdic in self.inspectItemArr) {
            //删除本地数据
            if([[inspectdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:inspectdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:inspectdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:INSPECT_ITEM andIdArr:deleteIdArr];
            
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveInspectItem:upArr];
        }
    }else{
        NSLog(@"巡检流程无数据更新");
    }
}


#pragma mark - 用户巡检项表

// 用户巡检项上行
- (void)uploadInspectUserItem {
    
    NSMutableArray *inspectUserItemArr = [self queryLocalModifyModAndAddIDForTable:INSPECT_USER_ITEM];
    if(inspectUserItemArr.count>0){
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:inspectUserItemArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_INSPECTUSERITEM_INSERT parameters:dic  success:^(id responseObject) {
            
            DeLog(@"上传用户巡检项返回%@",responseObject);
            if([[responseObject objectForKey:@"code"]isEqualToString:@"1"]){
                DeLog(@"用户巡检项上行成功%@",responseObject[@"msg"]);
                //修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:INSPECT_USER_ITEM andId:dic[@"id"]];
                }
                [self downloadInspectUserItem];
                
            }else{
                DeLog(@"用户巡检项上行失败");
            }
        } failure:^(NSError *error) {
            //                DeLog(@"用户巡检项上行失败：%@",error);
        }];
    }else{
        DeLog(@"新增巡检项无数据更新");
    }
}

// 查询巡检项实体表(用户巡检项表)
- (void)downloadInspectUserItem {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[self getIdAndModifyTimeFromTable:INSPECT_USER_ITEM];
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
        NSString *str=[self queryInspectProcessIds];
        NSString *inspectProcessIds = [LSUtility strbydan:str];
        if (inspectProcessIds && inspectProcessIds.length>0) {
            [dic setObject:inspectProcessIds forKey:@"inspectProcessIds"];
        }else{

            return ;
        }        //更新数据请求
        //        NSLog(@"用户巡检项入参：%@",dic);
        [LSHttpTool Post:URL_INSPECTUSERITEM_SELECT parameters:dic success:^(id responseObject) {
            
            NSString *code=[responseObject objectForKey:@"code"];
            //            NSLog(@"下载用户巡检项：%@",responseObject);
            if([code isEqualToString:@"1"]){
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.inspectUserItemArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateInspectUserItem];
                
            }else{
                NSLog(@"错误1545-%@",[responseObject objectForKey:@"msg"]);
            }
        } failure:^(NSError *error) {
            
        }];
    }
    else
    {
        // 本地数组转换成json
        NSString *str=[self queryInspectProcessIds] ;
        NSString *inspectProcessIds = [LSUtility strbydan:str];
        if (inspectProcessIds && inspectProcessIds.length>0) {
            [dic setObject:inspectProcessIds forKey:@"inspectProcessIds"];
        }else{
            return ;
        }        [dic setObject:@"" forKey:@"localdata"];
        //更新数据请求
        [LSHttpTool Post:URL_INSPECTUSERITEM_SELECT parameters:dic success:^(id responseObject) {
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]){
                
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.inspectUserItemArr addObject:mDict];
                }
                //执行本地数据更改方法
                [self updateInspectUserItem];
            }else{
                NSLog(@"错误%@",[responseObject objectForKey:@"msg"]);
            }
        } failure:^(NSError *error) {
            
        }];
    }
}

// 执行本地数据更改方法(用户巡检项表)
- (void)updateInspectUserItem {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.inspectUserItemArr.count > 0) {
        for (NSMutableDictionary  *inspectdic in self.inspectUserItemArr) {
            //删除本地数据
            if([[inspectdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:inspectdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:inspectdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:INSPECT_USER_ITEM andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveInspectUserItem:upArr];
        }
        
        if(deleteIdArr.count>0||upArr.count>0){
            NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjzz" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice];
        }
    }else{
        NSLog(@"用户巡检无数据更新");
    }
}


#pragma mark - 一键汇总表

// 一键汇总的上行
- (void)uploadInspectTotalRecord {
    
    NSMutableArray *inspectTotalArr=[self queryLocalModifyModAndAddIDForTable:INSPECT_TOTAL_RECORD];
    if(inspectTotalArr.count>0){
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:inspectTotalArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_INSPECTTOTALRECORD_INSERT parameters:dic  success:^(id responseObject) {
            
            if([[responseObject objectForKey:@"code"]isEqualToString:@"1"]){
                DeLog(@"一键汇总上行成功%@",responseObject[@"msg"]);
                //修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:INSPECT_TOTAL_RECORD andId:dic[@"id"]];
                }
                [self downloadInspectTotalRecord];
                
            }else{
                DeLog(@"一键汇总上行失败%@",responseObject[@"msg"]);
            }
        } failure:^(NSError *error) {
            DeLog(@"一键汇总上行失败%@",error);
        }];
    }else{
        NSLog(@"一键汇总无数据更新");
    }
}

// 查询一键汇总更新到本地
- (void)downloadInspectTotalRecord {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[self getIdAndModifyTimeFromTable:INSPECT_TOTAL_RECORD];
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
    }
    else
    {
        NSLog(@"一键汇总本地无数据");
        [dic setObject:@"" forKey:@"localdata"];
    }
    
    NSString *processids= [self queryInspectProcessIds];
    NSString *inspectProcessIds = [LSUtility strbydan:processids];
    if (inspectProcessIds && inspectProcessIds.length>0) {
        [dic setObject:inspectProcessIds forKey:@"inspectProcessIds"];
    }else{
        return ;
    }    DeLog(@"一键汇总入参：%@",dic);
    //更新数据请求
    [LSHttpTool Post:URL_INSPECTTOTALRECORD_SELECT parameters:dic success:^(id responseObject) {
        
        NSString *code=[responseObject objectForKey:@"code"];
        if([code isEqualToString:@"1"]){
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [self.inspectTotalRecordArr addObject:mDict];
            }
            //执行本地数据更改方法
            [self updateInspectTotalRecord];
        }else{
            DeLog(@"下行一键汇总错误%@",[responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        //        DeLog(@"下行一键汇总错误%@",error);
    }];
}

// 执行本地数据更改方法(一键汇总表)
- (void)updateInspectTotalRecord {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.inspectTotalRecordArr.count > 0) {
        for (NSMutableDictionary  *inspectdic in self.inspectTotalRecordArr) {
            //删除本地数据
            if([[inspectdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:inspectdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:inspectdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:INSPECT_TOTAL_RECORD andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveInspectTotalRecord:upArr];
        }
    }else{
        NSLog(@"一键汇总服务器无数据更新");
    }
}


#pragma mark - 巡检组表
// 巡检组，更新到本地
- (void)downloadInspectGroup {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[self getIdAndModifyTimeFromTable:INSPECT_GROUP];
    NSString *str=[self queryInspectProcessIds];
    
    NSString *inspectProcessIds = [LSUtility strbydan:str];
    if (inspectProcessIds && inspectProcessIds.length>0) {
        [dic setObject:inspectProcessIds forKey:@"inspectProcessIds"];
    }else{
        return ;
    }
    
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
    }
    else
    {
        [dic setObject:@"" forKey:@"localdata"];
    }
  
    //更新数据请求
    [LSHttpTool Post:URL_INSPECTGROUP_SELECT parameters:dic success:^(id responseObject) {
        
        NSString *code=[responseObject objectForKey:@"code"];
        if([code isEqualToString:@"1"]){
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [self.inspectGroupArr addObject:mDict];
            }
            //执行本地数据更改方法
            [self updateInspectGroup];
            
        }else{
            NSLog(@"错误--%@",[responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        
    }];
}

// 本地数据更新(巡检组表)
- (void)updateInspectGroup {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    // 是否存在更改的值
    if (self.inspectGroupArr.count>0) {
        for (NSMutableDictionary  *inspectdic in self.inspectGroupArr) {
            //删除本地数据
            if([[inspectdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:inspectdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:inspectdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:INSPECT_GROUP andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveInspectGroup:upArr];
        }
    }else{
        NSLog(@"巡检组无数据更新");
    }
}


#pragma mark - 巡检组用户表
// 巡检组用户，更新到本地
- (void)downloadInspectGroupUser {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[self getIdAndModifyTimeFromTable:INSPECT_GROUP_USER];
    NSString *str=[self queryInspectProcessIds] ;
    NSString *inspectProcessIds = [LSUtility strbydan:str];
    if (inspectProcessIds && inspectProcessIds.length>0) {
        [dic setObject:inspectProcessIds forKey:@"inspectProcessIds"];
    }else{
        return ;
    }
    
    if(arr!=nil)
    {
        // 本地数组转换成json
        NSString *jsonArr=[LSUtility dictionaryToJson:arr];
        [dic setObject:jsonArr forKey:@"localdata"];
    }
    else
    {
        NSLog(@"本地无数据");
        [dic setObject:@"" forKey:@"localdata"];
    }
    
    //更新数据请求
    [LSHttpTool Post:URL_INSPECTGROUPUSER_SELECT parameters:dic success:^(id responseObject) {
        
        NSString *code=[responseObject objectForKey:@"code"];
        if([code isEqualToString:@"1"]){
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [self.inspectGroupUserArr addObject:mDict];
            }
            //执行本地数据更改方法
            [self updateInspectGroupUser];
            
        }else{
            NSLog(@"巡检组用户错误-1996:%@",[responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        
    }];
}

// 本地数据更新(巡检组用户表)
-(void)updateInspectGroupUser {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.inspectGroupUserArr.count > 0) {
        for (NSMutableDictionary  *inspectdic in self.inspectGroupUserArr) {
            //删除本地数据
            if([[inspectdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:inspectdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:inspectdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:INSPECT_GROUP_USER andIdArr:deleteIdArr];
        }
        
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveInspectGroupUser:upArr];
        }
    }else{
        NSLog(@"巡检组用户无数据更新");
    }
}


#pragma mark - 查询巡检流程表ID 根据项目关联的巡检流程
- (NSString *)queryInspectProcessIds {
    
    DBHelper *helper = [DBHelper help];
    NSArray *dataArr= [helper DataBase:self.db selectKeyTypes:@{@"ID":@"text"} fromTable:INSPECT_PROCESS];
    // id存入数组
    NSMutableArray *idArray=[NSMutableArray array];
    if(dataArr.count>0){
        for (NSDictionary *dic in dataArr) {
            [idArray addObject:[dic objectForKey:@"ID"]];
        }
    }
    NSString *idsStr=[LSUtility dictionaryToJson_2:idArray];
    return idsStr;
}


#pragma mark - 流程表
// 上行流程表数据
- (void)uploadProces {
    NSMutableArray *processArr = [self queryLocalModifyModAndAddIDForTable:PROCESS];
    
    if(processArr.count>0){
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:processArr];
        [dic setValue:json forKey:@"list"];
       
        DeLog(@"流程入参：%@",dic);
        [LSHttpTool Post:URL_PROCESS_INSERT parameters:dic success:^(id responseObject) {
            
            DeLog(@"流程表%@",responseObject);
            // 下载流程
            [self downProcess];
            if ([responseObject[@"code"] isEqualToString:@"1"]){
                DeLog(@"上行流程数据成功");
                NSArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    // 修改本地数据
                    [self updateProcess:dic];
                }
            } else {
                DeLog(@"上行流程数据错误");
            }
        } failure:^(NSError *error) {
            //            DeLog(@"上行流程数据错误");
            //下载流程
            [self downProcess];
        }];
    }else{
        //下载流程
        [self downProcess];
        DeLog(@"上行流程无数据更新");
    }
}

// 下载流程服务器流程
- (void)downProcess {
    NSString *json = [self getLocalIDAndModifyTimeFrom:PROCESS];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:json forKey:@"localdata"];
    dispatch_group_enter(group);
    [LSHttpTool Post:URL_PROCESS_SELECT parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"1"]){
            NSLog(@"查询流程正确:%@",responseObject);
            NSArray *arr = responseObject[@"data"];
            // 同步本地数据库
            for (int i = 0; i < arr.count; i++) {
                NSDictionary *dic = arr[i];
                
                if ([dic[@"syncState"] intValue] == 2) {
                    [self.dProcessArr addObject:dic[@"id"]];
                } else {
                    [self.aProcessArr addObject:dic];
                }
            }
            // 删除本地流程
            [self deleteLocalData:self.dProcessArr fromTable:PROCESS];
            // 更新本地流程
            [self addProcessLocalData:self.aProcessArr];
            dispatch_group_leave(group);
            
        } else {
            dispatch_group_leave(group);
            NSLog(@"查询流程错误");
        }
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
        NSLog(@"查询流程请求超时");
    }];
}

// 服务器流程数据添加到本地
- (void)addProcessLocalData:(NSMutableArray *)updatePArr {
    if(updatePArr.count>0){
        //新增 更改方法
        [self.reData saveProcess:updatePArr];
    }
    // 查询流程记录
    [self downLoadProcessRecord:nil andView:nil];
}

// 查询服务器流程记录
- (void)downLoadProcessRecord:(NSArray *)processIDArr andView:(UIView *)view {
    NSArray *processIDArr1 = [self getLocalID:@"ID" fromTable:PROCESS];
    for (int i = 0; i < processIDArr1.count; i++) {
        
        dispatch_group_enter(group);
        // 从本地获取流程记录ID
        NSString *jsonStr = [self checkLocalIDAndModifyTimeFrom:PROCESS_RECORD where:@"PROCESS_ID" equal:processIDArr1[i]];
        // 拼接上传参数
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:jsonStr forKey:@"localdata"];
        [dic setObject:processIDArr1[i] forKey:@"processId"];
        
        // 向服务器查询数据
        [LSHttpTool Post:URL_PROCESSRECORD_SELECT parameters:dic success:^(id responseObject) {
            
            if ([responseObject[@"code"] isEqualToString:@"1"]){
                NSArray *flowRecordArr = responseObject[@"data"];
                // 删除记录数组
                NSMutableArray *DPRecordArr = [NSMutableArray array];
                // 更新记录数组
                NSMutableArray *pRArr = [NSMutableArray array];
                for (int j = 0; j < flowRecordArr.count; j++) {
                    NSDictionary *dic = flowRecordArr[j];
                    if ([dic[@"syncState"] intValue] == 2) {
                        [DPRecordArr addObject:dic[@"id"]];
                        
                    } else {
                        [pRArr addObject:dic];
                        //添加到新增附件id
                        [self.attachFileids addObject:dic[@"id"]];
                    }
                }
                // 删除本地流程记录
                [self deleteLocalData:DPRecordArr fromTable:PROCESS_RECORD];
                // 更新本地流程记录
                [self addRecordLocalData:pRArr];
                
            } else {
                NSLog(@"查询流程记录错误");
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    }
}

// 同步本地流程记录
- (void)addRecordLocalData:(NSArray *)arr {
    DBHelper *dbhelper=[DBHelper help];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    for (NSDictionary *dic in arr) {
        //字段及对应值
        NSDictionary *recordDic=[NSDictionary dictionary];
        recordDic = @{
                      @"ID":DEFISNUL(dic[@"id"]),
                      @"PRO_ID":DEFISNUL(dic[@"proId"]),
                      @"PROCESS_ID":DEFISNUL(dic[@"processId"]),
                      @"WEATHER":DEFISNUL(dic[@"weather"]),
                      @"ADDRESS_ID":DEFISNUL(dic[@"addressId"]),
                      @"ADDRES_INFO":DEFISNUL(dic[@"addressInfo"]),
                      @"PROCESS_TYPE":DEFISNUL(dic[@"processType"]),
                      @"PROCESS_STAGE":DEFISNUL(dic[@"processStage"]),
                      @"RECORD_USER":DEFISNUL(dic[@"recordUser"]),
                      @"PROBLEM_TYPE":DEFISNUL(dic[@"problemType"]),
                      @"RECORD_MASTER":DEFISNUL(dic[@"recordMaster"]),
                      @"RECIFY_USER":DEFISNUL(dic[@"recifyUser"]),
                      @"RECIFY_UNIT":DEFISNUL(dic[@"recifyUnit"]),
                      @"SEVERITY":DEFISNUL(dic[@"severity"]),
                      @"END_TIME":DEFISNUL(dic[@"endtime"]),
                      @"SEND_TIME":DEFISNUL(dic[@"sendtime"]),
                      @"SEND_TYPE":DEFISNUL(dic[@"sendtype"]),
                      @"PROCESS_TITLE":DEFISNUL(dic[@"processTitle"]),
                      @"PROCESS_CONTENT":DEFISNUL(dic[@"processContent"]),
                      @"PROCESS_REQUIRED":DEFISNUL(dic[@"processRequired"]),
                      @"PROCESS_DESC":DEFISNUL(dic[@"processDesc"]),
                      @"SUBMITTORS":DEFISNUL(dic[@"submittors"]),
                      @"PUT_USER":DEFISNUL(dic[@"putUser"]),
                      @"REVIEW_USER":DEFISNUL(dic[@"reviewUser"]),
                      @"REVIEW_OPINION":DEFISNUL(dic[@"reviewOpinion"]),
                      @"REVIEW_STATE":DEFISNUL(dic[@"reviewState"]),
                      @"FILEINFOS":DEFISNUL(dic[@"fileinfos"]),
                      @"EXTEND_INFO":DEFISNUL(dic[@"extendInfo"]),
                      @"CREATE_USER_NAME":DEFISNUL(dic[@"createusername"]),
                      @"CREATE_TIME":DEFISNUL(dic[@"createtime"]),
                      @"CREATE_IP":DEFISNUL(dic[@"createip"]),
                      @"MODIFY_USER_NAME":DEFISNUL(dic[@"modifyusername"]),
                      @"MODIFY_IP":DEFISNUL(dic[@"modifyip"]),
                      @"MODIFY_TIME":DEFISNUL(dic[@"modifytime"]),
                      @"LOCAL_MODIFY_USER_NAME":@"",
                      @"LOCAL_MODIFY_TIME":@"",
                      @"LOCAL_MODIFY_STATE":@"DOWNLOADED",
                      };
        BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:recordDic intoTable:PROCESS_RECORD];
        if(isAdd){
            NSLog(@"修改本地流程记录成功");
        }else{
            NSLog(@"修改本地流程记录失败");
        }
    }
    [db close];
}

// 服务器更新流程成功回调(修改本地数据状态)
- (void)updateProcess:(NSDictionary *)pIDic {
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSLog(@"number:%@",pIDic[@"processNumber"]);
    NSString *sql=@"";
    if(pIDic[@"processNumber"]){
        sql = [NSString stringWithFormat:@"UPDATE PROCESS SET LOCAL_MODIFY_STATE = '', PROCESS_NUMBER = '%@'  WHERE ID = '%@'",pIDic[@"processNumber"], pIDic[@"id"]];
    }else{
        sql = [NSString stringWithFormat:@"UPDATE PROCESS SET LOCAL_MODIFY_STATE = '' WHERE ID = '%@'", pIDic[@"id"]];
    }
    
    if ([db executeUpdate:sql]) {
        NSLog(@"修改流程状态成功");
    } else {
        NSLog(@"修改流程状态失败");
    }
    [db close];
}


#pragma mark - 流程记录表
- (void)uploadProcessRecord {
    NSMutableArray *processRecordArr = [self queryProcessRecordAddOrMod];
    
    if(processRecordArr.count>0){
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:processRecordArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_PROCESSRECORD_INSERT parameters:dic success:^(id responseObject) {
            
            if([[responseObject objectForKey:@"code"]isEqualToString:@"1"]){
                DeLog(@"流程记录上行成功%@",responseObject[@"msg"]);
                //修改本地状态
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:PROCESS_RECORD andId:dic[@"id"]];
                }
            }else{
                DeLog(@"流程记录上行失败%@",responseObject[@"msg"]);
            }
        } failure:^(NSError *error) {
            DeLog(@"流程记录上行失败%@",error);
        }];
    }
}

// 获取流程记录
- (NSMutableArray *)queryProcessRecordAddOrMod {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = @"SELECT * FROM PROCESS_RECORD WHERE LOCAL_MODIFY_STATE IN('ADD','MOD')";
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *jsonArr = [NSMutableArray array];
    
    while ([result next]) {
        NSDictionary *pragameDic=[NSDictionary dictionary];
        pragameDic=@{
                     @"id":[result stringForColumn:@"ID"],
                     @"proId":[result stringForColumn:@"PRO_ID"],
                     @"processId":[result stringForColumn:@"PROCESS_ID"],
                     @"weather":[result stringForColumn:@"WEATHER"],
                     @"addressId":[result stringForColumn:@"ADDRESS_ID"],
                     @"processType":[NSString stringWithFormat:@"%d", [result intForColumn:@"PROCESS_TYPE"]],
                     @"processStage":[NSString stringWithFormat:@"%d", [result intForColumn:@"PROCESS_STAGE"]],
                     @"recordUser":[result stringForColumn:@"RECORD_USER"],
                     @"problemType":[result stringForColumn:@"PROBLEM_TYPE"],
                     @"recordMaster":[result stringForColumn:@"RECORD_MASTER"],
                     @"recifyUser":[result stringForColumn:@"RECIFY_USER"],
                     @"recifyUnit":[result stringForColumn:@"RECIFY_UNIT"],
                     @"severity":[result stringForColumn:@"SEVERITY"],
                     @"endtime":[result stringForColumn:@"END_TIME"],
                     @"sendtime":[result stringForColumn:@"SEND_TIME"],
                     @"sendtype":[result stringForColumn:@"SEND_TYPE"],
                     @"processTitle":[result stringForColumn:@"PROCESS_TITLE"],
                     @"processRequired":[result stringForColumn:@"PROCESS_REQUIRED"],
                     @"processContent":[result stringForColumn:@"PROCESS_CONTENT"],
                     @"processDesc":[result stringForColumn:@"PROCESS_DESC"],
                     @"submittors":[result stringForColumn:@"SUBMITTORS"],
                     @"putUser":[result stringForColumn:@"PUT_USER"],
                     @"reviewUser":[result stringForColumn:@"REVIEW_USER"],
                     @"reviewOpinion":[result stringForColumn:@"REVIEW_OPINION"],
                     @"reviewState":[result stringForColumn:@"REVIEW_STATE"],
                     @"fileinfos":[result stringForColumn:@"FILEINFOS"],
                     @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                     @"createtime":[result stringForColumn:@"CREATE_TIME"],
                     @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                     @"createip":[result stringForColumn:@"CREATE_IP"],
                     @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                     @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                     @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"],
                     };
        [jsonArr addObject:pragameDic];
    }
    [db close];
    return jsonArr;
}


#pragma mark - 见证取样流程表
- (void)uploadSamplesProcess {
    // 查找本地见证取样表由变更的数据
    NSArray *samplesProcess = [self querySamplesProcessAddOrMod];
    if (samplesProcess.count>0) {
        // 本地有变更的见证取流程表 插入服务器
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:samplesProcess];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_SAMPLE_PROCESS_INSERT parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                DeLog(@"见证取样流程上行成功");
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    //修改本地状态
                    [self updateStateForTable:SAMPLE_PROCESS andId:dic[@"id"]];
                }
                // 查询见证取样流程
                [self downloadSampleProcess];
                
            } else {
                DeLog(@"本见证取样流程上行失败");
                // 查询见证取样流程
                [self downloadSampleProcess];
            }
        } failure:^(NSError *error) {
            NSLog(@"见证取样流程上行请求超时");
            // 查询见证取样流程
            [self downloadSampleProcess];
        }];
    } else {
        DeLog(@"见证取样上行数据无");
        // 查询见证取样流程
        [self downloadSampleProcess];
    }
}

// 查找本地见证取样表有变更的数据
- (NSArray *)querySamplesProcessAddOrMod {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql =@"SELECT * FROM SAMPLE_PROCESS WHERE LOCAL_MODIFY_STATE IN ('ADD','MOD')";
    
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *sampleProcessArr = [NSMutableArray array];
    while ([result next]) {
        NSDictionary *pragameDic = [NSDictionary dictionary];
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"processNumber":[result stringForColumn:@"PROCESS_NUMBER"],
                       @"sampleName":[result stringForColumn:@"SAMPLE_NAME"],
                       @"sampleDesc":[result stringForColumn:@"SAMPLE_DESC"],
                       @"sampleNumber":[result stringForColumn:@"SAMPLE_NUMBER"],
                       @"sampleGetTime":[result stringForColumn:@"SAMPLE_GET_TIME"],
                       @"sampleGetAddress":[result stringForColumn:@"SAMPLE_GET_ADDRESS"],
                       @"sampleGetAddressInfo":[result stringForColumn:@"SAMPLE_GET_ADDRESS_INFO"],
                       @"sampleWinessUser":[result stringForColumn:@"SAMPLE_WINESS_USER"],
                       @"sampleQrCode":[result stringForColumn:@"SAMPLE_QR_CODE"],
                       @"sampleSecurityCode":[result stringForColumn:@"SAMPLE_SECURITY_CODE"],
                       @"sampleProcessState":[result stringForColumn:@"SAMPLE_PROCESS_STATE"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":DEFISNUL([result stringForColumn:@"MODIFY_TIME"]),
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"],
                       };
        [sampleProcessArr addObject:pragameDic];
    }
    [db close];
    return sampleProcessArr;
}

// 查询见证取样流程
- (void)downloadSampleProcess {
    NSString *json = [self getLocalIDAndModifyTimeFrom:SAMPLE_PROCESS];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:json forKey:@"localdata"];
    dispatch_group_enter(group);
    [LSHttpTool Post:URL_SAMPLE_PROCESS_GET parameters:dic success:^(id responseObject) {
        NSLog(@"见证取样流程%@", responseObject);
        
        if ([responseObject[@"code"] isEqualToString:@"1"]){
            NSLog(@"查询见证取样流程正确");
            NSArray *arr = responseObject[@"data"];
            // 删除本地见证取样ID数组
            NSMutableArray *deleteSPArr = [NSMutableArray array];
            // 更新本地见证取样数组
            NSMutableArray *updateSPArr = [NSMutableArray array];
            // 同步本地数据库
            for (int i = 0; i < arr.count; i++) {
                NSDictionary *dic = arr[i];
                if ([dic[@"syncState"] intValue] == 2) {
                    [deleteSPArr addObject:dic[@"id"]];
                } else {
                    [updateSPArr addObject:dic];
                }
            }
            // 删除本地见证取样流程
            [self deleteLocalData:deleteSPArr fromTable:SAMPLE_PROCESS];
            // 更新本地见证取样流程
            [self updateLocalSampleProcess:updateSPArr];
            // 查询本地见证取样流程ID
            NSArray *samplePIDArr = [self getLocalID:@"ID" fromTable:SAMPLE_PROCESS];
            // 下载见证取样流程记录
            [self downloadSampleProcessRecord:samplePIDArr];
            dispatch_group_leave(group);
            
        } else {
            // 查询本地见证取样流程ID
            NSArray *samplePIDArr = [self getLocalID:@"ID" fromTable:SAMPLE_PROCESS];
            // 下载见证取样流程记录
            [self downloadSampleProcessRecord:samplePIDArr];
            dispatch_group_leave(group);
            NSLog(@"查询见证取样流程错误");
        }
    } failure:^(NSError *error) {
        // 查询本地见证取样流程ID
        NSArray *samplePIDArr = [self getLocalID:@"ID" fromTable:SAMPLE_PROCESS];
        // 下载见证取样流程记录
        [self downloadSampleProcessRecord:samplePIDArr];
        dispatch_group_leave(group);
        NSLog(@"查询见证取样流程请求超时");
    }];
}

#pragma mark - 查询服务器见证取样流程记录
- (void)downloadSampleProcessRecord:(NSArray *)processIDArr {
    for (int i = 0; i < processIDArr.count; i++) {
        // 从本地获取见证取样流程记录ID
        NSString *jsonStr = [self checkLocalIDAndModifyTimeFrom:SAMPLE_PROCESS_RECORD where:@"PROCESS_ID" equal:processIDArr[i]];
        dispatch_group_enter(group);
        // 拼接上传参数
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:jsonStr forKey:@"localdata"];
        [dic setObject:processIDArr[i] forKey:@"processId"];
        // 向服务器查询数据
        [LSHttpTool Post:URL_SAMPLE_PROCESS_RECORD_GET parameters:dic success:^(id responseObject) {
            
            NSLog(@"见证取样流程记录：%@",responseObject);
            if ([responseObject[@"code"] isEqualToString:@"1"]){
                NSLog(@"查询见证取样流程记录正确");
                NSArray *flowRecordArr = responseObject[@"data"];
                // 删除见证取样记录数组
                NSMutableArray *dSPRecordArr = [NSMutableArray array];
                // 更新见证取样记录数组
                NSMutableArray *pSampleRecordArr = [NSMutableArray array];
                for (int j = 0; j < flowRecordArr.count; j++) {
                    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:flowRecordArr[j]];
                    
                    for (int k = 0; k < 2; k++) {
                        if (k == 0) {
                            [dic setObject:@"4" forKey:@"processType"];
                            if ([dic[@"syncState"] intValue] == 2) {
                                [dSPRecordArr addObject:dic[@"id"]];
                                
                            } else {
                                [pSampleRecordArr addObject:dic];
                            }
                        } else if (k == 1) {
                            NSMutableDictionary *dic1 = [[NSMutableDictionary alloc] initWithDictionary:dic];
                            
                            if ([dic[@"syncState"] intValue] == 2) {
                                [dSPRecordArr addObject:dic[@"id"]];
                                
                            } else {
                                [pSampleRecordArr addObject:dic1];
                                [self.attachFileids addObject:dic[@"id"]];
                            }
                        }
                    }
                }
                // 删除本地见证取样流程记录
                [self deleteLocalData:dSPRecordArr fromTable:SAMPLE_PROCESS_RECORD];
                if(pSampleRecordArr.count>0){
                    // 更新本地见证取样流程记录
                    [self updateLocalSampleProcessRecord:pSampleRecordArr];
                }
            } else {
                NSLog(@"查询见证取样流程记录错误:msg:%@",responseObject[@"msg"]);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            NSLog(@"查询见证取样流程记录请求超时");
        }];
    }
}

// 更新本地见证取样流程记录
- (void)updateLocalSampleProcessRecord:(NSArray *)arr {
    DBHelper *dbhelper=[DBHelper help];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    for (NSDictionary *dic in arr) {
        //字段及对应值
        NSDictionary *recordDic=[NSDictionary dictionary];
        recordDic = @{
                      @"ID":DEFISNUL(dic[@"id"]),
                      @"PROCESS_ID":DEFISNUL(dic[@"processId"]),
                      @"PRO_ID":DEFISNUL(dic[@"proId"]),
                      @"RECORD_TIME":DEFISNUL(dic[@"recordTime"]),
                      @"RECORD_USER":DEFISNUL(dic[@"recordUser"]),
                      @"RECORD_CONTENT":DEFISNUL(dic[@"recordContent"]),
                      @"SAMPLE_WITNESS_RESULT":@"",
                      @"SAMPLE_WITNESS_SCORE":@"",
                      @"SAMPLE_WITNESS_REVIEW":@"",
                      @"SAMPLE_CHECK_TORF_RESULT":@"",
                      @"SAMPLE_CHECK_TORF_DESC":@"",
                      @"SAMPLE_CHECK_RESULT":@"",
                      @"SAMPLE_CHECK_DESC":@"",
                      @"SAMPLE_CHECK_RESULT_DESC":@"",
                      @"SAMPLE_CHECK_RESULT_SCORE":@"",
                      @"SAMPLE_PROCESS_STATE":DEFISNUL(dic[@"sampleProcessState"]),
                      @"RECORD_DESC":@"",
                      @"EXTEND_INFO":@"",
                      @"CREATE_USER_NAME":DEFISNUL(dic[@"createusername"]),
                      @"CREATE_TIME":DEFISNUL(dic[@"createtime"]),
                      @"CREATE_IP":DEFISNUL(dic[@"createip"]),
                      @"MODIFY_USER_NAME":DEFISNUL(dic[@"modifyusername"]),
                      @"MODIFY_IP":DEFISNUL(dic[@"modifyip"]),
                      @"MODIFY_TIME":DEFISNUL(dic[@"modifytime"]),
                      @"LOCAL_MODIFY_USER_NAME":@"",
                      @"LOCAL_MODIFY_TIME":@"",
                      @"LOCAL_MODIFY_STATE":@"DOWNLOADED",
                      };
        BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:recordDic intoTable:SAMPLE_PROCESS_RECORD];
        if(isAdd){
            NSLog(@"更新本地见证取样流程记录成功");
        }else{
            NSLog(@"更新本地见证取样流程记录失败");
        }
    }
    [db close];
}


#pragma mark- 更新本地见证取样流程
- (void)updateLocalSampleProcess:(NSArray *)sampleProcessArr {
    DBHelper *dbhelper=[DBHelper help];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    for (NSDictionary *dic in sampleProcessArr) {
        // 要更新的数据
        NSDictionary *sampleProcessdic;
        // 查询本地是否有本条数据
        NSString *IDSql = [NSString stringWithFormat:@"SELECT ID FROM SAMPLE_PROCESS WHERE ID = '%@'", dic[@"id"]];
        FMResultSet *result = [db executeQuery:IDSql];
        NSString *processID;
        while ([result next]) {
            processID = [result stringForColumn:@"ID"];
        }
        // 如果本地有本条流程
        if (processID) {
            // 查询当前的本地最后修改时间
            NSString *modSql = [NSString stringWithFormat:@"SELECT MODIFY_TIME FROM SAMPLE_PROCESS WHERE ID = '%@'", dic[@"id"]];
            FMResultSet *result = [db executeQuery:modSql];
            NSString *modifyTime;
            while ([result next]) {
                modifyTime = [result stringForColumn:@"MODIFY_TIME"];
            }
            
            // 比较最后修改时间
            int cha = [LSUtility compareLocalDate:modifyTime withServerDate:dic[@"modifytime"]];
            
            if (cha == 1 || !modifyTime) {
                sampleProcessdic = [self createSampleProcess:dic];
            }
            
        } else {    // 如果本地没有本条流程(直接增加)
            sampleProcessdic = [self createSampleProcess:dic];
        }
        
        // 如果数据存在就更新
        if (sampleProcessdic) {
            // 更新见证取样流程表
            BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:sampleProcessdic intoTable:SAMPLE_PROCESS];
            if(isAdd){
                NSLog(@"更新本地见证取样流程成功");
            }else{
                NSLog(@"更新本地见证取样流程失败");
            }
        }
    }
    [db close];
}

// 拼接见证取样流程表的数据
- (NSDictionary *)createSampleProcess:(NSDictionary *)dic {
    // 字段及对应值
    NSDictionary *sampleProdessDic = [NSDictionary dictionary];
    sampleProdessDic = @{
                         @"ID":DEFISNUL(dic[@"id"]),
                         @"PROCESS_NUMBER":DEFISNUL(dic[@"processNumber"]),
                         @"PRO_ID":DEFISNUL(dic[@"proId"]),
                         @"SAMPLE_NAME":DEFISNUL(dic[@"sampleName"]),
                         @"SAMPLE_DESC":DEFISNUL(dic[@"sampleDesc"]),
                         @"SAMPLE_NUMBER":DEFISNUL(dic[@"sampleNumber"]),
                         @"SAMPLE_MENUFACTURER":@"",
                         @"SAMPLE_VARIETY":@"",
                         @"SAMPLE_OUT_GROUND_NUMBER":@"",
                         @"SAMPLE_VARIETY_MODEL":@"",
                         @"SAMPLE_IN_TIME":@"",
                         @"SAMPLE_IN_AMOUNT":@"",
                         @"SAMPLE_REPRESENT_AMOUT":@"",
                         @"SAMPLE_GROUP_AMOUNT":@"",
                         @"SAMPLE_GET_TIME":DEFISNUL(dic[@"sampleGetTime"]),
                         @"SAMPLE_GET_ADDRESS":DEFISNUL(dic[@"sampleGetAddress"]),
                         @"SAMPLE_GET_ADDRESS_INFO":DEFISNUL(dic[@"sampleGetAddressInfo"]),
                         @"SAMPLE_USE_POSITION":@"",
                         @"SAMPLE_PROJECT":@"",
                         @"SAMPLE_PRODUCT_STANDARD":@"",
                         @"SAMPLE_CHECK_STANDARD":@"",
                         @"SAMPLE_DESIGN_REQUIRED":@"",
                         @"SAMPLE_GET_USER":@"",
                         @"SAMPLE_WINESS_USER":DEFISNUL(dic[@"sampleWinessUser"]),
                         @"SAMPLE_CHECK_USER":@"",
                         @"SAMPLE_CHECK_UNIT":@"",
                         @"SAMPLE_QR_CODE":DEFISNUL(dic[@"sampleQrCode"]),
                         @"SAMPLE_SECURITY_CODE":DEFISNUL(dic[@"sampleSecurityCode"]),
                         @"SAMPLE_PROCESS_STATE":DEFISNUL(dic[@"sampleProcessState"]),
                         @"SAMPLE_PROCESS_DESC":@"",
                         @"EXTEND_INFO":DEFISNUL(dic[@"extendInfo"]),
                         @"CREATE_USER_NAME":DEFISNUL(dic[@"createusername"]),
                         @"CREATE_TIME":DEFISNUL(dic[@"createtime"]),
                         @"CREATE_IP":DEFISNUL(dic[@"createip"]),
                         @"MODIFY_USER_NAME":DEFISNUL(dic[@"modifyusername"]),
                         @"MODIFY_IP":DEFISNUL(dic[@"modifyip"]),
                         @"MODIFY_TIME":DEFISNUL(dic[@"modifytime"]),
                         @"LOCAL_MODIFY_USER_NAME":@"",
                         @"LOCAL_MODIFY_TIME":@"",
                         @"LOCAL_MODIFY_STATE":@"DOWNLOADED",
                         };
    return sampleProdessDic;
}


#pragma mark - 见证取样流程记录(新增 编辑数据上行)
- (void)uploadSampleProcessRecord {
    // 获取要新增的数据
    NSArray *ProcessRecordArr = [self querySampleProcessRecordAddOrMod];
    if(ProcessRecordArr.count>0){
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *json=[LSUtility dictionaryToJson_4:ProcessRecordArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_SAMPLE_PROCESS_RECORD_INSERT parameters:dic success:^(id responseObject) {
            
            if ([responseObject[@"code"] isEqualToString:@"1"]){
                DeLog(@"见证取样流程记录上行成功");
                
                NSMutableArray *array=responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    //修改本地状态
                    [self updateStateForTable:URL_SAMPLE_PROCESS_RECORD_INSERT andId:dic[@"id"]];
                }
            } else {
                DeLog(@"见证取样流程记录上行失败:%@",responseObject);
            }
        } failure:^(NSError *error) {
            DeLog(@"见证取样流程记录上行失败:%@",error);
        }];
    }else{
        DeLog(@"见证取样流程记录上行数据无");
    }
}

// 获取见证取样流程记录（ADD,MOD）
- (NSMutableArray *)querySampleProcessRecordAddOrMod {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql =@"SELECT * FROM SAMPLE_PROCESS_RECORD WHERE LOCAL_MODIFY_STATE in('ADD','MOD')";
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *samplePRArr = [NSMutableArray array];
    
    while ([result next]) {
        NSDictionary *pragameDic = [NSDictionary dictionary];
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"processId":[result stringForColumn:@"PROCESS_ID"],
                       @"recordTime":[result stringForColumn:@"RECORD_TIME"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordContent":[result stringForColumn:@"RECORD_CONTENT"],
                       @"sampleProcessState":[result stringForColumn:@"SAMPLE_PROCESS_STATE"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":DEFISNUL([result stringForColumn:@"MODIFY_TIME"]),
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"],
                       };
        [samplePRArr addObject:pragameDic];
    }
    [db close];
    return samplePRArr;
}


#pragma mark - 查询服务器项目信息
- (void)downloadProject {
    NSString *json = [self getLocalIDAndModifyTimeFrom:PROJECT];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:json forKey:@"localdata"];
    [dic setObject:DEF_PERSISTENT_GET_OBJECT(@"realname") forKey:@"usernames"];
    DeLog(@"项目表入参：%@",dic);
    dispatch_group_enter(group);
    [LSHttpTool Post:URL_PROJECT_SELECT parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"1"]){
            NSArray *arr = responseObject[@"data"];
            // 删除项目数组
            NSMutableArray *DProjectArr = [NSMutableArray array];
            // 更新项目数组
            NSMutableArray *updateProjectArr = [NSMutableArray array];
            for (int i = 0; i < arr.count; i++) {
                NSMutableDictionary *dic = arr[i];
                if ([dic[@"syncState"] intValue] == 2) {
                    [DProjectArr addObject:dic[@"id"]];
                    //删除项目相关联数据
                    NSString *proid=dic[@"id"];
                    DBHelper *helper=[DBHelper help];
                    [helper DataBase:self.db createTable:PROJECT_USER keyTypes:@{@"proId":proid}];
                    [helper DataBase:self.db createTable:PROJECT_UNIT keyTypes:@{@"proId":proid}];
                    [helper DataBase:self.db createTable:ADDRESS keyTypes:@{@"proId":proid}];
                } else {
                    [updateProjectArr addObject:dic];
                }
                
                NSString *ids=dic[@"id"];
                if([LSUtility queryProjectForId:ids]){
                    [self.proidsArr addObject:dic[@"id"]];
                }
            }
            
            [self deleteLocalData:DProjectArr fromTable:PROJECT];
            [self syncLocalProjectData:updateProjectArr];
            dispatch_group_leave(group);
            
        } else {
            NSLog(@"返回项目信息错误");
            //项目人员
            [self downloadProUsers];
            //项目地址表
            [self downloadProjectAddress];
            //单位
            [self downloadUnit];
            dispatch_group_leave(group);
        }
    } failure:^(NSError *error) {
        //   NSLog(@"项目信息请求超时");
        //项目人员
        [self downloadProUsers];
        //项目地址表
        [self downloadProjectAddress];
        //单位
        [self downloadUnit];
        dispatch_group_leave(group);
    }];
}

// 同步本地项目信息
- (void)syncLocalProjectData:(NSArray *)projectArr {
    DBHelper *dbhelper=[DBHelper help];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    for (NSDictionary *dic in projectArr) {
        //字段及对应值
        NSDictionary *projectDic=[NSDictionary dictionary];
        projectDic = @{
                       @"ID":DEFISNUL(dic[@"id"]),
                       @"PROJECT_NAME":DEFISNUL(dic[@"proName"]),
                       @"PROJECT_NUMBER":DEFISNUL(dic[@"proNumber"]),
                       @"PROJECT_STATE":DEFISNUL(dic[@"proState"]),
                       @"STATE":DEFISNUL(dic[@"state"]),
                       @"CREATE_USER_NAME":DEFISNUL(dic[@"createusername"]),
                       @"CREATE_TIME":DEFISNUL(dic[@"createtime"]),
                       @"CREATE_IP":DEFISNUL(dic[@"createip"]),
                       @"MODIFY_USER_NAME":DEFISNUL(dic[@"modifyusername"]),
                       @"MODIFY_IP":DEFISNUL(dic[@"modifyip"]),
                       @"MODIFY_TIME":DEFISNUL(dic[@"modifytime"]),
                       @"LOCAL_MODIFY_USER_NAME":@"",
                       @"LOCAL_MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_STATE":@"DOWNLOADED",
                       @"EXTEND_INFO":DEFISNUL(dic[@"extendInfo"]),
                       };
        BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:projectDic intoTable:PROJECT];
        if(isAdd){
            //            NSLog(@"修改本地项目信息成功");
        }else{
            NSLog(@"修改本地项目信息失败");
        }
    }
    //项目人员
    [self downloadProUsers];
    //项目地址表
    [self downloadProjectAddress];
    //单位
    [self downloadUnit];
    [db close];
}

// 项目人员查询（修改）
- (void)downloadProUsers {
    NSArray *arr = [LSUtility getProjectUser:@"proUsers"proIds:self.proidsArr];
    if (arr.count>0) {
        NSString *jsonStr = [LSUtility toJSONData:arr];
        NSMutableDictionary *parameterDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:jsonStr, @"localdata", nil];
        [LSHttpTool Post:URL_PROJECTUSER_SELECT parameters:parameterDic success:^(id responseObject) {
            
            NSLog(@"项目人员返回：%@",responseObject);
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]) {
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.proUsers addObject:mDict];
                }
                //执行本地数据更改方法
                [self updataProUser];
                
            }else{
                NSLog(@"项目人员错误 2689-%@",responseObject);
            }
        } failure:^(NSError *error) {
            
        }];
    }else{
        NSMutableDictionary *parameterDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"", @"localdata", nil];
        [LSHttpTool Post:URL_PROJECTUSER_SELECT parameters:parameterDic success:^(id responseObject) {
            
            NSLog(@"项目人员返回：%@",responseObject);
            NSString *code=[responseObject objectForKey:@"code"];
            if([code isEqualToString:@"1"]) {
                for (NSDictionary *mudic in responseObject[@"data"]) {
                    //得到服务器返回的字典
                    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                    [self.proUsers addObject:mDict];
                }
                //执行本地数据更改方法
                [self updataProUser];
                
            }else{
                NSLog(@"项目人员错误 2717-%@",responseObject);
            }
        } failure:^(NSError *error) {
        }];
    }
}

// 更新本地项目人员表
- (void)updataProUser {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.proUsers.count > 0) {
        for (NSMutableDictionary  *workdic in self.proUsers) {
            //删除本地数据
            if([[workdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:workdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:workdic];
            }
        }
        
        if(upArr.count>0){
            NSMutableArray *proidsArray=[NSMutableArray array];
            //清除以前的项目相关联人员
            for (int i=0; i<upArr.count; i++) {
                NSDictionary *dic=upArr[i];
                NSString *proId=dic[@"proId"];
                [proidsArray addObject:proId];
            }
            //去重
            proidsArray =[proidsArray valueForKeyPath:@"@distinctUnionOfObjects.self"];
            DBHelper *helper=[DBHelper help];
            for (NSString *ids in proidsArray) {
                [helper DataBase:self.db createTable:PROJECT_USER keyTypes:@{@"id":ids}];
            }
            //新增 更改方法
            [self.reData saveProUsers:upArr];
        }
    }else{
        NSLog(@"项目人员无数据更新");
    }
}

#pragma mark - 查询项目地址
- (void)downloadProjectAddress {
    
    NSArray *arr = [LSUtility getProjectUser:@"add" proIds:self.proidsArr];
    // 去掉这句同步出错时 地址附件会丢失
    [self getIdAndModifyTimeFromTable:ADDRESS];
    dispatch_group_enter(group);
    if(arr != nil){
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        NSMutableDictionary *parameterDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:jsonStr, @"localdata", nil];
        DeLog(@"项目地址入参：%@",parameterDic);
        //向服务器查询数据
        [LSHttpTool Post:URL_ADDRESS_SELECT parameters:parameterDic success:^(id responseObject) {
            
            if ([responseObject[@"code"] isEqualToString:@"1"]){
                NSArray *flowRecordArr = responseObject[@"data"];
                DeLog(@"项目地址返回%@",flowRecordArr);
                // 删除本地项目地址数组
                NSMutableArray *DProjectAddressArr = [NSMutableArray array];
                NSMutableArray *updatePAddressArr = [NSMutableArray array];
                for (int j = 0; j < flowRecordArr.count; j++) {
                    NSDictionary *dic = flowRecordArr[j];
                    if ([dic[@"syncState"] intValue] == 2) {
                        [DProjectAddressArr addObject:dic[@"id"]];
                    } else if ([dic[@"syncState"] intValue] == 0) {
                        [updatePAddressArr addObject:dic];
                        [self.attachFileids addObject:dic[@"id"]];
                    }
                }
                
                [self deleteLocalData:DProjectAddressArr fromTable:ADDRESS];
                [self syncLocalAddressData:updatePAddressArr];
                if(updatePAddressArr.count>0){
                    // 查询附件(本地没有的)
                    // [self downloadAttachment2:updatePAddressArr];
                }
            } else {
                NSLog(@"地址请求错误797：%@",responseObject);
            }
            dispatch_group_leave(group);
            
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
            NSLog(@"地址请求超时:%@",error);
        }];
    } else {
        NSDictionary *parameterDic=@{@"localdata":@""};
        // 向服务器查询数据
        dispatch_group_enter(group);
        [LSHttpTool Post:URL_ADDRESS_SELECT parameters:parameterDic success:^(id responseObject) {
            
            DeLog(@"地址：%@",responseObject);
            if ([responseObject[@"code"] isEqualToString:@"1"]){
                //NSLog(@"返回项目地址正确");
                NSArray *flowRecordArr = responseObject[@"data"];
                // 删除本地项目地址数组
                NSMutableArray *DProjectAddressArr = [NSMutableArray array];
                NSMutableArray *updatePAddressArr = [NSMutableArray array];
                
                for (int j = 0; j < flowRecordArr.count; j++) {
                    NSDictionary *dic = flowRecordArr[j];
                    if ([dic[@"syncState"] intValue] == 2) {
                        [DProjectAddressArr addObject:dic[@"id"]];
                        
                    } else if ([dic[@"syncState"] intValue] == 0) {
                        [updatePAddressArr addObject:dic];
                        [self.attachFileids addObject:dic[@"id"]];
                    }
                }
                
                [self deleteLocalData:DProjectAddressArr fromTable:ADDRESS];
                [self syncLocalAddressData:updatePAddressArr];
            }else{
                NSLog(@"地址请求错误834：%@",responseObject);
            }
            
            dispatch_group_leave(group);
        } failure:^(NSError *error) {
            NSLog(@"地址请求超时:%@",error);
        }];
    }
}

// 同步本地项目地址
- (void)syncLocalAddressData:(NSArray *)projectAddressArr {
    DBHelper *dbhelper=[DBHelper help];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    //    if(projectAddressArr.count>0){
    //        //        清空本地数据表
    //        DBHelper *helper=[DBHelper help];
    //        [helper clearDatabase:self.db  from:ADDRESS];
    //    }
    
    for (NSDictionary *dic in projectAddressArr) {
        //字段及对应值
        NSDictionary *AddressDic=[NSDictionary dictionary];
        AddressDic = @{
                       @"ID":DEFISNUL(dic[@"id"]),
                       @"PRO_ID":DEFISNUL(dic[@"proId"]),
                       @"PATENT_ID":DEFISNUL(dic[@"parentId"]),
                       @"ADDRESS_NAME":DEFISNUL(dic[@"addName"]),
                       @"ADDRESS_TYPE":DEFISNUL(dic[@"addType"]),
                       @"A__LONG":DEFISNUL(dic[@"along"]),
                       @"A__LAT":DEFISNUL(dic[@"alat"]),
                       @"A__HEIGHT":DEFISNUL(dic[@"aheight"]),
                       @"B__LONG":DEFISNUL(dic[@"blong"]),
                       @"B__LAT":DEFISNUL(dic[@"blat"]),
                       @"B__HEIGHT":DEFISNUL(dic[@"bheight"]),
                       @"C__LONG":DEFISNUL(dic[@"clong"]),
                       @"C__LAT":DEFISNUL(dic[@"clat"]),
                       @"C__HEIGHT":DEFISNUL(dic[@"cheight"]),
                       @"D__LONG":DEFISNUL(dic[@"dlong"]),
                       @"D__LAT":DEFISNUL(dic[@"dlat"]),
                       @"D__HEIGHT":DEFISNUL(dic[@"dheight"]),
                       @"STATE":DEFISNUL(dic[@"state"]),
                       @"SCALE":DEFISNUL(dic[@"scale"]),
                       @"IMAGE_INFO":DEFISNUL(dic[@"imageInfo"]),
                       @"IMAGE_INFO_DESC":DEFISNUL(dic[@"imageInfoDesc"]),
                       @"EXTEND_INFO":DEFISNUL(dic[@"extendInfo"]),
                       @"CREATE_USER_NAME":DEFISNUL(dic[@"createusername"]),
                       @"CREATE_TIME":DEFISNUL(dic[@"createtime"]),
                       @"CREATE_IP":DEFISNUL(dic[@"createip"]),
                       @"MODIFY_USER_NAME":DEFISNUL(dic[@"modifyusername"]),
                       @"MODIFY_IP":DEFISNUL(dic[@"modifyip"]),
                       @"MODIFY_TIME":DEFISNUL(dic[@"modifytime"]),
                       @"LOCAL_MODIFY_USER_NAME":@"",
                       @"LOCAL_MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_STATE":@"DOWNLOADED",
                       @"LEFT_NAME":DEFISNUL(dic[@"leftName"]),
                       @"RIGHT_NAME":DEFISNUL(dic[@"rightName"]),
                       @"DISTANCE_OF_LEFTANDRIGHT":DEFISNUL(dic[@"distanceOfLeftandright"]),
                       };
        
        BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:AddressDic intoTable:ADDRESS];
        if(isAdd){
            NSLog(@"添加本地项目地址成功");
        }else{
            NSLog(@"添加本地项目地址失败");
        }
    }
    [db close];
}

// 查询项目单位
- (void)downloadUnit {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arr=[self getIdAndModifyTimeFromTable:UNIT];
    if(arr!=nil){
        // 本地数组转换成json
        NSString *json=[LSUtility dictionaryToJson:arr];
        [dic setObject:json forKey:@"localdata"];
    }else{
        [dic setObject:@"" forKey:@"localdata"];
    }
    [LSHttpTool Post:URL_UNIT_SELECT parameters:dic success:^(id responseObject) {
        
        NSString *code=[responseObject objectForKey:@"code"];
        if([code isEqualToString:@"1"]){
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [self.unitArr addObject:mDict];
            }
            //执行本地数据更改方法
            [self updataUnit];
            
        }else{
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        
    }];
}

// 更新项目单位信息
- (void)updataUnit {
    //需要删除的本地数据数组
    NSMutableArray *deleteIdArr=[NSMutableArray array];
    //需要更改的本地数据数组
    NSMutableArray *upArr=[NSMutableArray array];
    //是否存在更改的值
    if (self.unitArr.count > 0) {
        for (NSMutableDictionary  *workdic in self.unitArr) {
            //删除本地数据
            if([[workdic objectForKey:@"syncState"]intValue]==2){
                [deleteIdArr addObject:workdic[@"id"]];
            }
            else
            {
                //修改或新增本地数据
                [upArr addObject:workdic];
            }
        }
        
        if(deleteIdArr.count>0){
            //删除方法
            [LSUtility deleteTable:UNIT andIdArr:deleteIdArr];
        }
        if(upArr.count>0){
            //新增 更改方法
            [self.reData saveUnit:upArr];
        }
    }else{
        NSLog(@"单位无数据更新");
    }
}


#pragma mark - 查询服务器项目概况
- (void)downloadProjectProfile {
    // 从本地查项目ID
    NSArray *projectIDArr = [self getLocalID:@"ID" fromTable:PROJECT];
    NSMutableArray *parameterArr = [NSMutableArray array];
    for (int i = 0; i < projectIDArr.count; i++) {
        // 获取项目概况ID和最后修改时间
        NSMutableArray *array = [self getLocalIDAndModifyTimeFrom:PRO_ENGINEER_SURVEY where:@"PRO_ID" equal222:projectIDArr[i]];
        //没有相关的项目概览 list传空
        NSDictionary * dic;
        if(!array){
            dic= @{@"proId":projectIDArr[i], @"list":@[]};
        }else{
            dic=  @{@"proId":projectIDArr[i], @"list":array};
        }
        [parameterArr addObject:dic];
    }
    
    // 把参数转化为JSON字符串
    NSString *parameterStr = [LSUtility toJSONData:parameterArr];
    // 拼接到可变字典
    NSMutableDictionary *parameterDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:parameterStr, @"localdata", nil];
    // 发送请求
    [LSHttpTool Post:URL_PROJECTENGINEERSURVEY_SELEC parameters:parameterDic success:^(id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"1"]) {
            NSLog(@"返回项目概况正确");
            NSArray *arr=responseObject[@"data"];
            // 删除项目概况数组
            NSMutableArray *DProjectProfileArr = [NSMutableArray array];
            // 更新项目概况数组
            NSMutableArray *updatePProfileArr = [NSMutableArray array];
            for (int i = 0; i < arr.count; i++) {
                NSMutableDictionary *dic = arr[i];
                if ([dic[@"syncState"] intValue] == 2) {
                    [DProjectProfileArr addObject:dic[@"id"]];
                } else {
                    [updatePProfileArr addObject:dic];
                }
            }
            [self deleteLocalData:DProjectProfileArr fromTable:PRO_ENGINEER_SURVEY];
            [self syncLocalProfileData:updatePProfileArr];
            
        } else {
            NSLog(@"返回项目概况错误");
        }
    } failure:^(NSError *error) {
        NSLog(@"请求项目概况超时");
    }];
}

// 项目概览
- (NSMutableArray *)getLocalIDAndModifyTimeFrom:(NSString *)tableName where:(NSString *)condition equal222:(NSString *)equal {
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    if (![db open]) {
        [db open];
    }
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT ID, MODIFY_TIME FROM %@ WHERE %@ = '%@' AND LOCAL_MODIFY_STATE NOT IN('ADD','MOD')", tableName, condition, equal];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    while ([result next]) {
        NSString *ID = [result stringForColumn:@"ID"];
        if ([ID isEqualToString:@""]) {
            continue;
        }
        NSString *modifyTime = DEFISNUL([result stringForColumn:@"MODIFY_TIME"]);
        NSDictionary *pragameDic = @{@"id":ID, @"modifyTime":modifyTime};
        [array addObject:pragameDic];
    }
    
//    NSString *jsonStr = [LSUtility toJSONData:array];
    [db close];
    return array;
}

// 同步本地项目概况
- (void)syncLocalProfileData:(NSArray *)profileArr {
    DBHelper *dbhelper=[DBHelper help];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    for (NSDictionary *dic in profileArr) {
        //字段及对应值
        NSDictionary *profileDic=[NSDictionary dictionary];
        profileDic = @{
                       @"ID":DEFISNUL(dic[@"id"]),
                       @"PRO_ID":DEFISNUL(dic[@"proId"]),
                       @"CITY_ID":DEFISNUL(dic[@"cityId"]),
                       @"CITY_CODE":DEFISNUL(dic[@"cityCode"]),
                       @"ENGINEER_ADDRESS":DEFISNUL(dic[@"engineerAddress"]),
                       @"BUILDING_SCALE":DEFISNUL(dic[@"buildingScale"]),
                       @"FREE_SERVICE_TIME":DEFISNUL(dic[@"freeServiceTime"]),
                       @"GUARANTEE_TIME":DEFISNUL(dic[@"guaranteeTime"]),
                       @"SERVICE_TIME":DEFISNUL(dic[@"serviceTime"]),
                       @"CONSTRACT_AMOUNT":DEFISNUL(dic[@"constractAmount"]),
                       @"INVESTMENT_AMOUNT":DEFISNUL(dic[@"investmentAmount"]),
                       @"ENGINEER_TYPE":DEFISNUL(dic[@"engineerType"]),
                       @"INVESTMENT_NATURE":DEFISNUL(dic[@"investmentNature"]),
                       @"START_WORK_TIME":DEFISNUL(dic[@"startworkTime"]),
                       @"COMPLETE_WORK_TIME":DEFISNUL(dic[@"completeworkTime"]),
                       @"PRO_SURVEY":DEFISNUL(dic[@"proSurvey"]),
                       @"PRO_ENGINEER_DESC":DEFISNUL(dic[@"proEngineerDesc"]),
                       @"CREATE_USER_NAME":DEFISNUL(dic[@"createusername"]),
                       @"CREATE_TIME":DEFISNUL(dic[@"createtime"]),
                       @"CREATE_IP":DEFISNUL(dic[@"createip"]),
                       @"MODIFY_USER_NAME":DEFISNUL(dic[@"modifyusername"]),
                       @"MODIFY_IP":DEFISNUL(dic[@"modifyip"]),
                       @"MODIFY_TIME":DEFISNUL(dic[@"modifytime"]),
                       @"LOCAL_MODIFY_USER_NAME":@"",
                       @"LOCAL_MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_STATE":@"DOWNLOADED",
                       @"EXTEND_INFO":DEFISNUL(dic[@"extendInfo"]),
                       };
        BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:profileDic intoTable:PRO_ENGINEER_SURVEY];
        if(isAdd) {
            
        } else {
            NSLog(@"修改本地项目概况失败");
        }
    }
    [db close];
}


#pragma mark - 同步巡视表

// 本地变更的给服务器
- (void)localPatrolUpdateServer {
    // 查询本地有变更的巡视
    NSMutableArray *patrolArr = [self queryLocalModifyModAndAddIDForTable:PATROL_RECORD];
    
    if (patrolArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:patrolArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_PATROLRECORD_INSERT_OR_REPLACE_LIST parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                //修改本地状态
                NSMutableArray *array = responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:PATROL_RECORD andId:dic[@"id"]];
                }
                // 刷新巡视列表页
                if (array.count > 0) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPatrolList" object:nil];
                }
                // 查询下载服务器有变更巡视表
                [self downServerPatrol];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                // 查询下载服务器有变更巡视表
                [self downServerPatrol];
            }
        } failure:^(NSError *error) {
            // 查询下载服务器有变更巡视表
            [self downServerPatrol];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        // 查询下载服务器有变更巡视表
        [self downServerPatrol];
    }
}

// 查询下载服务器有变更巡视
- (void)downServerPatrol {
    // 获取巡视id与最近修改时间
    NSArray *arr = [self getIdAndModifyTimeFromTable:PATROL_RECORD];
    NSMutableDictionary *paramedic = [NSMutableDictionary dictionary];
    if (arr.count > 0) {
        // 本地数组转换成json
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        // 传参
        [paramedic setObject:jsonStr forKey:@"localdata"];
        
    } else {
        [paramedic setObject:@"" forKey:@"localdata"];
    }
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if (role&&role.length>0) {
        [paramedic setObject:role forKey:@"userType"];
    }
    dispatch_group_enter(group);
    // 更新数据请求
    [LSHttpTool Post:URL_PATROLRECORD_SELECT parameters:paramedic success:^(id responseObject) {
        
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            NSMutableArray *patrolArr = [NSMutableArray array];
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [patrolArr addObject:mDict];
            }
            // 更新巡视表
            [self updateLocalPatrol:patrolArr];
            // 刷新巡视列表页
            if (patrolArr.count > 0) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPatrolList" object:nil];
            }
        } else {
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
        dispatch_group_leave(group);
        
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    }];
}

// 更新本地巡视数据库
-(void)updateLocalPatrol:(NSArray *)dataArr {
    // 是否存在更改的值
    if (dataArr.count > 0) {
        
        // 需要删除的本地数据数组
        NSMutableArray *deleteIdArr = [NSMutableArray array];
        // 需要更新的数据
        NSMutableArray *updateArr = [NSMutableArray array];
        for (NSMutableDictionary *workdic in dataArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"] intValue] == 2){
                [deleteIdArr addObject:workdic[@"id"]];
                
            // 修改或新增本地数据
            } else {
                [updateArr addObject:workdic];
            }
        }
        
        // 删除数据
        if (deleteIdArr.count > 0) {
            [LSUtility deleteTable:PATROL_RECORD andIdArr:deleteIdArr];
        }
        
        // 更新数据
        if (updateArr.count > 0) {
            [self.reData savePatrolRecordArray:updateArr];
            
            // 附件下载
            for (NSDictionary *dic in updateArr) {
                [self.attachFileids addObject:dic[@"id"]];
            }
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 同步安全基本信息表

// 本地变更的给服务器
- (void)localSafeBasicUpdateServer {
    // 查询本地有变更的安全基本信息
    NSMutableArray *safeBasicArr = [self queryLocalModifyModAndAddIDForTable:SAFE_RECORD_BASIC];
    if (safeBasicArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:safeBasicArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_SAFE_RECORDBASIC_INSERT_OR_REPLACE_LIST parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                // 修改本地状态
                NSMutableArray *array = responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:SAFE_RECORD_BASIC andId:dic[@"id"]];
                }
                // 刷新安全列表页
                if (array.count > 0) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSafeList" object:nil];
                }
                // 查询下载服务器有变更安全基本信息表
                [self downServerSafeBasic];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                // 查询下载服务器有变更安全基本信息表
                [self downServerSafeBasic];
            }
        } failure:^(NSError *error) {
            // 查询下载服务器有变更安全基本信息表
            [self downServerSafeBasic];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        // 查询下载服务器有变更安全基本信息表
        [self downServerSafeBasic];
    }
}

// 查询下载服务器有变更的安全基本信息
- (void)downServerSafeBasic {
    // 获取巡视id与最近修改时间
    NSArray *arr = [self getIdAndModifyTimeFromTable:SAFE_RECORD_BASIC];
    NSMutableDictionary *paramedic = [NSMutableDictionary dictionary];
    if (arr.count > 0) {
        // 本地数组转换成json
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        // 传参
        [paramedic setObject:jsonStr forKey:@"localdata"];
        
    } else {
        [paramedic setObject:@"" forKey:@"localdata"];
    }
    
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if (role&&role.length>0) {
        [paramedic setObject:role forKey:@"userType"];
    }
    dispatch_group_enter(group);
    // 更新数据请求
    [LSHttpTool Post:URL_SAFE_RECORDBASIC_SELECT parameters:paramedic success:^(id responseObject) {
        
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            NSMutableArray *patrolArr = [NSMutableArray array];
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [patrolArr addObject:mDict];
            }
            // 更新巡视表
            [self updateLocalSafeBasic:patrolArr];
            // 刷新巡视列表页
            if (patrolArr.count > 0) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSafeList" object:nil];
            }
        } else {
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
        dispatch_group_leave(group);
        
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    }];
}

// 更新本地安全基本信息数据库
-(void)updateLocalSafeBasic:(NSArray *)dataArr {
    // 是否存在更改的值
    if (dataArr.count > 0) {
        
        // 需要删除的本地数据数组
        NSMutableArray *deleteIdArr = [NSMutableArray array];
        // 需要更新的数据
        NSMutableArray *updateArr = [NSMutableArray array];
        for (NSMutableDictionary *workdic in dataArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"] intValue] == 2){
                [deleteIdArr addObject:workdic[@"id"]];
                
                // 修改或新增本地数据
            } else {
                [updateArr addObject:workdic];
            }
        }
        
        // 删除数据
        if (deleteIdArr.count > 0) {
            [LSUtility deleteTable:SAFE_RECORD_BASIC andIdArr:deleteIdArr];
        }
        
        // 更新数据
        if (updateArr.count > 0) {
            [self.reData saveSecurityRecordBasic:updateArr];
            
            // 附件下载
            for (NSDictionary *dic in updateArr) {
                [self.attachFileids addObject:dic[@"id"]];
            }
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 同步安全施工三类人员表

// 本地变更的给服务器
- (void)localSafeConstructUpdateServer {
    // 查询本地有变更的安全基本信息
    NSMutableArray *safeBasicArr = [self queryLocalModifyModAndAddIDForTable:SAFE_CONSTRUCT];
    if (safeBasicArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:safeBasicArr];
        [dic setValue:json forKey:@"list"];
        
        [LSHttpTool Post:URL_SAFE_CONSTRUCT_INSERT_OR_REPLACE_LIST parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                //修改本地状态
                NSMutableArray *array = responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:SAFE_CONSTRUCT andId:dic[@"id"]];
                }
                // 查询下载服务器有变更安全施工三类人员表
                [self downServerSafeConstruct];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                // 查询下载服务器有变更安全施工三类人员表
                [self downServerSafeConstruct];
            }
        } failure:^(NSError *error) {
            // 查询下载服务器有变更安全施工三类人员表
            [self downServerSafeConstruct];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        // 查询下载服务器有变更安全施工三类人员表
        [self downServerSafeConstruct];
    }
}

// 查询下载服务器有变更的安全施工三类人员
- (void)downServerSafeConstruct {
    // 获取巡视id与最近修改时间
    NSArray *arr = [self getIdAndModifyTimeFromTable:SAFE_CONSTRUCT];
    NSMutableDictionary *paramedic = [NSMutableDictionary dictionary];
    if (arr.count > 0) {
        // 本地数组转换成json
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        // 传参
        [paramedic setObject:jsonStr forKey:@"localdata"];
        
    } else {
        [paramedic setObject:@"" forKey:@"localdata"];
    }
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if (role&&role.length>0) {
        [paramedic setObject:role forKey:@"userType"];
    }
    
    dispatch_group_enter(group);
    // 更新数据请求
    [LSHttpTool Post:URL_SAFE_CONSTRUCT_SELECT parameters:paramedic success:^(id responseObject) {
        
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            NSMutableArray *patrolArr = [NSMutableArray array];
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [patrolArr addObject:mDict];
            }
            // 更新本地安全施工三类人员数据库
            [self updateLocalSafeConstruct:patrolArr];

        } else {
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
        dispatch_group_leave(group);
        
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    }];
}

// 更新本地安全施工三类人员数据库
-(void)updateLocalSafeConstruct:(NSArray *)dataArr {
    // 是否存在更改的值
    if (dataArr.count > 0) {
        
        // 需要删除的本地数据数组
        NSMutableArray *deleteIdArr = [NSMutableArray array];
        // 需要更新的数据
        NSMutableArray *updateArr = [NSMutableArray array];
        for (NSMutableDictionary *workdic in dataArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"] intValue] == 2){
                [deleteIdArr addObject:workdic[@"id"]];
                // 修改或新增本地数据
            } else {
                [updateArr addObject:workdic];
            }
        }
        
        // 删除数据
        if (deleteIdArr.count > 0) {
            [LSUtility deleteTable:SAFE_CONSTRUCT andIdArr:deleteIdArr];
        }
        
        // 更新数据
        if (updateArr.count > 0) {
            [self.reData saveThreeTypePeople:updateArr];
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 特种作业人员持证情况

// 本地变更的给服务器
- (void)localSafeSpecialTypeUpdateServer {
    // 查询本地有变更的安全基本信息
    NSMutableArray *safeBasicArr = [self queryLocalModifyModAndAddIDForTable:SAFE_SPECIAL_TYPE];
    if (safeBasicArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:safeBasicArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_SAFE_SPECIALTYPE_INSERT_OR_REPLACE_LIST parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                //修改本地状态
                NSMutableArray *array = responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:SAFE_SPECIAL_TYPE andId:dic[@"id"]];
                }
                // 查询下载服务器有变更特种作业人员表
                [self downServerSafeSpecialType];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                // 查询下载服务器有变更特种作业人员表
                [self downServerSafeSpecialType];
            }
        } failure:^(NSError *error) {
            // 查询下载服务器有变更特种作业人员表
            [self downServerSafeSpecialType];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        // 查询下载服务器有变更特种作业人员表
        [self downServerSafeSpecialType];
    }
}

// 查询下载服务器有变更特种作业人员表
- (void)downServerSafeSpecialType {
    // 获取巡视id与最近修改时间
    NSArray *arr = [self getIdAndModifyTimeFromTable:SAFE_SPECIAL_TYPE];
    NSMutableDictionary *paramedic = [NSMutableDictionary dictionary];
    if (arr.count > 0) {
        // 本地数组转换成json
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        // 传参
        [paramedic setObject:jsonStr forKey:@"localdata"];
        
    } else {
        [paramedic setObject:@"" forKey:@"localdata"];
    }
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if (role&&role.length>0) {
        [paramedic setObject:role forKey:@"userType"];
    }
    dispatch_group_enter(group);
    // 更新数据请求
    [LSHttpTool Post:URL_SAFE_SPECIALTYPE_SELECT parameters:paramedic success:^(id responseObject) {
        
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            NSMutableArray *patrolArr = [NSMutableArray array];
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [patrolArr addObject:mDict];
            }
            // 更新安全表
            [self updateLocalSafeSpecial:patrolArr];
    
        } else {
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
        dispatch_group_leave(group);
        
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    }];
}

// 更新本地安全特种作业人员表
-(void)updateLocalSafeSpecial:(NSArray *)dataArr {
    // 是否存在更改的值
    if (dataArr.count > 0) {
        
        // 需要删除的本地数据数组
        NSMutableArray *deleteIdArr = [NSMutableArray array];
        // 需要更新的数据
        NSMutableArray *updateArr = [NSMutableArray array];
        for (NSMutableDictionary *workdic in dataArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"] intValue] == 2){
                [deleteIdArr addObject:workdic[@"id"]];
                
                // 修改或新增本地数据
            } else {
                [updateArr addObject:workdic];
            }
        }
        
        // 删除数据
        if (deleteIdArr.count > 0) {
            [LSUtility deleteTable:SAFE_SPECIAL_TYPE andIdArr:deleteIdArr];
        }
        
        // 更新数据
        if (updateArr.count > 0) {
            [self.reData saveSpecialOperationsPersonnel:updateArr];
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 同步安全监理巡查
// 本地变更的给服务器
- (void)localSecurityPatrolUpdateServer {
    // 查询本地有变更的安全基本信息
    NSMutableArray *safeBasicArr = [self queryLocalModifyModAndAddIDForTable:SECURITY_PATROL];
    if (safeBasicArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:safeBasicArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_SAFE_SAFEPATROL_INSERT_OR_REPLACE_LIST parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                //修改本地状态
                NSMutableArray *array = responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:SECURITY_PATROL andId:dic[@"id"]];
                }
                // 查询下载服务器有变更监理安全巡查
                [self downServerSecurityPatrolType];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                // 查询下载服务器有变更监理安全巡查
                [self downServerSecurityPatrolType];
            }
        } failure:^(NSError *error) {
            // 查询下载服务器有变更监理安全巡查
            [self downServerSecurityPatrolType];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        // 查询下载服务器有变更监理安全巡查
        [self downServerSecurityPatrolType];
    }
}

// 查询下载服务器有变更监理安全巡查
- (void)downServerSecurityPatrolType {
    // 获取巡视id与最近修改时间
    NSArray *arr = [self getIdAndModifyTimeFromTable:SECURITY_PATROL];
    NSMutableDictionary *paramedic = [NSMutableDictionary dictionary];
    if (arr.count > 0) {
        // 本地数组转换成json
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        // 传参
        [paramedic setObject:jsonStr forKey:@"localdata"];
        
    } else {
        [paramedic setObject:@"" forKey:@"localdata"];
    }
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if (role&&role.length>0) {
        [paramedic setObject:role forKey:@"userType"];
    }
    
    dispatch_group_enter(group);
    // 更新数据请求
    [LSHttpTool Post:URL_SAFE_SAFEPATROL_SELECT parameters:paramedic success:^(id responseObject) {
        
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            NSMutableArray *patrolArr = [NSMutableArray array];
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [patrolArr addObject:mDict];
            }
            // 更新本地监理安全巡查
            [self updateLocalSecurityPatrol:patrolArr];
    
        } else {
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
        dispatch_group_leave(group);
        
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    }];
}

// 更新本地监理安全巡查
-(void)updateLocalSecurityPatrol:(NSArray *)dataArr {
    // 是否存在更改的值
    if (dataArr.count > 0) {
        
        // 需要删除的本地数据数组
        NSMutableArray *deleteIdArr = [NSMutableArray array];
        // 需要更新的数据
        NSMutableArray *updateArr = [NSMutableArray array];
        for (NSMutableDictionary *workdic in dataArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"] intValue] == 2){
                [deleteIdArr addObject:workdic[@"id"]];
                
                // 修改或新增本地数据
            } else {
                [updateArr addObject:workdic];
            }
        }
        
        // 删除数据
        if (deleteIdArr.count > 0) {
            [LSUtility deleteTable:SECURITY_PATROL andIdArr:deleteIdArr];
        }
        
        // 更新数据
        if (updateArr.count > 0) {
            [self.reData saveSecurityPatrol:updateArr];
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 危险性较大工程监理检查

// 本地变更的给服务器
- (void)localSafeDangerUpdateServer {
    // 查询本地有变更的安全基本信息
    NSMutableArray *safeBasicArr = [self queryLocalModifyModAndAddIDForTable:SAFE_DANGER];
    if (safeBasicArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:safeBasicArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_SAFE_DANGER_INSERT_OR_REPLACE_LIST parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                //修改本地状态
                NSMutableArray *array = responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:SAFE_DANGER andId:dic[@"id"]];
                }
                // 查询下载服务器有变更危险性较大工程监理检查
                [self downServerSafeDanger];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                // 查询下载服务器有变更危险性较大工程监理检查
                [self downServerSafeDanger];
            }
        } failure:^(NSError *error) {
            // 查询下载服务器有变更危险性较大工程监理检查
            [self downServerSafeDanger];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        // 查询下载服务器有变更危险性较大工程监理检查
        [self downServerSafeDanger];
    }
}

// 查询下载服务器有变更危险性较大工程监理检查
- (void)downServerSafeDanger {
    // 获取巡视id与最近修改时间
    NSArray *arr = [self getIdAndModifyTimeFromTable:SAFE_DANGER];
    NSMutableDictionary *paramedic = [NSMutableDictionary dictionary];
    if (arr.count > 0) {
        // 本地数组转换成json
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        // 传参
        [paramedic setObject:jsonStr forKey:@"localdata"];
        
    } else {
        [paramedic setObject:@"" forKey:@"localdata"];
    }
    
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if (role&&role.length>0) {
        [paramedic setObject:role forKey:@"userType"];
    }
    dispatch_group_enter(group);
    // 更新数据请求
    [LSHttpTool Post:URL_SAFE_DANGER_SELECT parameters:paramedic success:^(id responseObject) {
        
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            NSMutableArray *patrolArr = [NSMutableArray array];
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [patrolArr addObject:mDict];
            }
            // 更新本地危险性较大工程监理检查
            [self updateLocalSafeDanger:patrolArr];
            
        } else {
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
        dispatch_group_leave(group);
        
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    }];
}

// 更新本地危险性较大工程监理检查
-(void)updateLocalSafeDanger:(NSArray *)dataArr {
    // 是否存在更改的值
    if (dataArr.count > 0) {
        
        // 需要删除的本地数据数组
        NSMutableArray *deleteIdArr = [NSMutableArray array];
        // 需要更新的数据
        NSMutableArray *updateArr = [NSMutableArray array];
        for (NSMutableDictionary *workdic in dataArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"] intValue] == 2){
                [deleteIdArr addObject:workdic[@"id"]];
                
                // 修改或新增本地数据
            } else {
                [updateArr addObject:workdic];
            }
        }
        
        // 删除数据
        if (deleteIdArr.count > 0) {
            [LSUtility deleteTable:SAFE_DANGER andIdArr:deleteIdArr];
        }
        
        // 更新数据
        if (updateArr.count > 0) {
            [self.reData saveDangerousWork:updateArr];
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 施工设备进场

// 本地变更的给服务器
- (void)localSafeDeviceUpdateServer {
    // 查询本地有变更的安全基本信息
    NSMutableArray *safeBasicArr = [self queryLocalModifyModAndAddIDForTable:SAFE_CONSTRUCT_DEVICE];
    if (safeBasicArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *json = [LSUtility dictionaryToJson_4:safeBasicArr];
        [dic setValue:json forKey:@"list"];
        [LSHttpTool Post:URL_SAFE_CONSTRUCTDEVICE_INSERT_OR_REPLACE_LIST parameters:dic success:^(id responseObject) {
            
            if ([[responseObject objectForKey:@"code"]isEqualToString:@"1"]) {
                //修改本地状态
                NSMutableArray *array = responseObject[@"data"];
                for (NSDictionary *dic in array) {
                    [self updateStateForTable:SAFE_CONSTRUCT_DEVICE andId:dic[@"id"]];
                }
                // 查询下载服务器有变更施工设备进场
                [self downServerSafeDevice];
                
            } else {
                DeLog(@"本地记录无数据更新失败");
                // 查询下载服务器有变更施工设备进场
                [self downServerSafeDevice];
            }
        } failure:^(NSError *error) {
            // 查询下载服务器有变更施工设备进场
            [self downServerSafeDevice];
        }];
    } else {
        DeLog(@"本地记录无数据更新");
        // 查询下载服务器有变更施工设备进场
        [self downServerSafeDevice];
    }
}

// 查询下载服务器有变更施工设备进场
- (void)downServerSafeDevice {
    // 获取巡视id与最近修改时间
    NSArray *arr = [self getIdAndModifyTimeFromTable:SAFE_CONSTRUCT_DEVICE];
    NSMutableDictionary *paramedic = [NSMutableDictionary dictionary];
    if (arr.count > 0) {
        // 本地数组转换成json
        NSString *jsonStr = [LSUtility dictionaryToJson:arr];
        // 传参
        [paramedic setObject:jsonStr forKey:@"localdata"];
        
    } else {
        [paramedic setObject:@"" forKey:@"localdata"];
    }
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if (role&&role.length>0) {
        [paramedic setObject:role forKey:@"userType"];
    }
    
    dispatch_group_enter(group);
    // 更新数据请求
    [LSHttpTool Post:URL_SAFE_CONSTRUCTDEVICE_SELECT parameters:paramedic success:^(id responseObject) {
        
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            NSMutableArray *patrolArr = [NSMutableArray array];
            for (NSDictionary *mudic in responseObject[@"data"]) {
                //得到服务器返回的字典
                NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:mudic];
                [patrolArr addObject:mDict];
            }
            // 更新本地施工设备进场
            [self updateLocalSafeDevice:patrolArr];
            
        } else {
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
        }
        dispatch_group_leave(group);
        
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
    }];
}

// 更新本地危险性较大工程监理检查
-(void)updateLocalSafeDevice:(NSArray *)dataArr {
    // 是否存在更改的值
    if (dataArr.count > 0) {
        
        // 需要删除的本地数据数组
        NSMutableArray *deleteIdArr = [NSMutableArray array];
        // 需要更新的数据
        NSMutableArray *updateArr = [NSMutableArray array];
        for (NSMutableDictionary *workdic in dataArr) {
            // 删除本地数据
            if([[workdic objectForKey:@"syncState"] intValue] == 2){
                [deleteIdArr addObject:workdic[@"id"]];
                
                // 修改或新增本地数据
            } else {
                [updateArr addObject:workdic];
            }
        }
        
        // 删除数据
        if (deleteIdArr.count > 0) {
            [LSUtility deleteTable:SAFE_CONSTRUCT_DEVICE andIdArr:deleteIdArr];
        }
        
        // 更新数据
        if (updateArr.count > 0) {
            [self.reData saveWorkDeviceApproach:updateArr];
        }
    } else {
        NSLog(@"用户无数据更新");
    }
}


#pragma mark - 查询服务器附件表
- (void)downloadAttachmentFromServer:(UIView *)view isLoad:(BOOL)load andExit:(BOOL)exit {
    
    NSMutableDictionary *parameDic=[NSMutableDictionary dictionary];
    NSString *fileids = [LSUtility dictionaryToJson_5:self.attachFileids];
    // fileIds 参数
    [parameDic setObject:fileids forKey:@"fileIds"];
    // localdata 参数
    NSString *localStr = [self getLocalIDAndModifyTimeFrom:ATTACHMENT];
    [parameDic setObject:localStr forKey:@"localdata"];
  
    // 向服务器查询数据
    [LSHttpTool Post:URL_ATTACHMENT_SELECT parameters:parameDic success:^(id responseObject) {
       
        
        NSLog(@"附件表返回：%@\nmsg:%@",responseObject,responseObject[@"msg"]);
        // 附件返回成功
        if ([responseObject[@"code"] isEqualToString:@"1"]){
            NSArray *flowRecordArr = responseObject[@"data"];
            // 删除本地附件表数组
            NSMutableArray *DattachentArr = [NSMutableArray array];
            for (int j = 0; j < flowRecordArr.count; j++) {
                NSDictionary *dic = flowRecordArr[j];
                if ([dic[@"syncState"] intValue] == 2) {
                    [DattachentArr addObject:dic[@"id"]];
                } else {
                    [self.attachArr addObject:dic];
                    //[self syncLocalAttachmentData:dic];
                }
            }

            // 不存在附件下载  附件为0 执行这个 退出登录
            if (self.attachArr.count==0) {
                if(self.blockSyncOver){
                    self.blockSyncOver();
                }
                if (view) {
                    [LSUtility hideMBProgress:view];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [LSUtility hideMBProgressNOAnimation:view];
                        [view removeFromSuperview];
                    });
                }
            }
           
            // 存在附件下载
            else{
                __block typeof(self) weakSelf = self;
                self.reData.blockSyncOver=^{
                    if(weakSelf.blockSyncOver){
                        weakSelf.blockSyncOver();
                    }
                };
                if (view) {
                    [LSUtility hideMBProgress:view];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [LSUtility hideMBProgressNOAnimation:view];
                        [view removeFromSuperview];
                    });
                }
            }
           
            //执行本地附件表更改方法
            if(load){
                [self updateAttachment];
                
            } else {
                [self updateAttachment2];
            }
            
            if(!exit){
                //同步数据检测
                [[NSNotificationCenter defaultCenter] postNotificationName:@"checkSyncSucceed" object:nil];
            }
          
//            [self deleteLocalData:DattachentArr fromTable:ATTACHMENT];
           
        }
        // 附件返回失败
        else {
            if (view) {
                [LSUtility hideMBProgress:view];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [LSUtility hideMBProgressNOAnimation:view];
                    [view removeFromSuperview];
                });
                [MBProgressHUD showError:@"服务器附件异常!" toView:view];
            }
            if(self.blockSyncOver){
                self.blockSyncOver();
            }
        }
    } failure:^(NSError *error) {
        if (view) {
            [LSUtility hideMBProgress:view];
            dispatch_async(dispatch_get_main_queue(), ^{
                [LSUtility hideMBProgressNOAnimation:view];
                [view removeFromSuperview];
                
            });
            
            if (!exit) {
                //同步数据检测
                [[NSNotificationCenter defaultCenter] postNotificationName:@"checkSyncSucceed" object:nil];
            }
            [MBProgressHUD showError:@"附件请求超时!" toView:view];
        }
        if (self.blockSyncOver) {
            self.blockSyncOver();
        }
        
    }];
}

// 显示进度条
- (void)updateAttachment {
    if(self.attachArr.count>0) {
        //NSLog(@"附件同步下载");
        //新增 更改方法
        self.reData.completedCount=0;
        [self.reData saveAttachment:self.attachArr andDownLoad:YES];
        [self.reData syncFileImage2];
    }
}

// 不显示进度条
- (void)updateAttachment2 {
    if(self.attachArr.count>0) {
        //NSLog(@"附件同步下载");
        //新增 更改方法
        self.reData.completedCount=0;
        [self.reData saveAttachment:self.attachArr andDownLoad:YES];
        [self.reData syncFileImage];
    }
}

// 同步本地附件
- (void)syncLocalAttachmentData:(NSDictionary *)dic {
    //字段及对应值
    NSDictionary *attachmentDic=[NSDictionary dictionary];
    attachmentDic = @{
                      @"ID":dic[@"id"] ? dic[@"id"] : @"",
                      @"FILE_TYPE_ID":dic[@"fileTypeId"] ? dic[@"fileTypeId"] : @"",
                      @"FILE_ID":dic[@"fileid"] ? dic[@"fileid"] : @"",
                      @"PRO_ID":dic[@"proId"] ? dic[@"proId"] : @"",
                      @"FILE_NAME":dic[@"filename"] ? dic[@"filename"] : @"",
                      @"FILE_SIZE":dic[@"filesize"] ? dic[@"filesize"] : @"",
                      @"FILE_SUFFIX":dic[@"filesuffix"] ? dic[@"filesuffix"] : @"",
                      @"FILE_PATH":dic[@"filepath"] ? dic[@"filepath"] : @"",
                      @"FILE_DESC":dic[@"fileDesc"] ? dic[@"fileDesc"] : @"",
                      @"FILE_STATE":dic[@"fileState"] ? dic[@"fileState"] : @"",
                      @"EXTEND_INFO":dic[@"extendInfo"] ? dic[@"extendInfo"] : @"",
                      @"CREATE_USER_NAME":dic[@"createusername"] ? dic[@"createusername"] : @"",
                      @"CREATE_TIME":dic[@"createtime"] ? dic[@"createtime"] : @"",
                      @"CREATE_IP":dic[@"createip"] ? dic[@"createip"] : @"",
                      @"MODIFY_IP":DEFISNUL(dic[@"modifyip"]),
                      @"MODIFY_TIME":DEFISNUL(dic[@"modifytime"]),
                      @"LOCAL_MODIFY_USER_NAME":@"",
                      @"LOCAL_MODIFY_TIME":@"",
                      @"LOCAL_MODIFY_STATE":@"DOWNLOADED",
                      };
    DBHelper *dbhelper=[DBHelper help];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:attachmentDic intoTable:ATTACHMENT];
    if(isAdd){
        //        NSLog(@"修改本地附件成功");
    }else{
        NSLog(@"修改本地附件失败");
    }
    [db close];
    /*
     *   执行下载操作
     **/
    dataInit *download=[[dataInit alloc]init];
    [download downLoadImage:dic[@"id"] andFileName:dic[@"filename"] andJumpBar:NO];
}


#pragma mark - 本地有变更的数据 返回 id
- (NSMutableArray *)queryLocalModifyModAndAddIDForTable:(NSString *)table {
    [self.db open];
    NSString *sql = [NSString stringWithFormat:@"select id from %@ where LOCAL_MODIFY_STATE in ('ADD','MOD')", table];
    
    // 存储表id数据
    NSMutableArray *idArray = [NSMutableArray array];
    FMResultSet *resultSet= [self.db executeQuery:sql];
    while ([resultSet next]) {
        NSString *ids=[resultSet stringForColumn:@"id"];
        [idArray addObject:ids];
        
        // 记录表 日记表 广告表 日志表 流程记录表 巡检路程记录表  见证取样流程记录表 地址表  需要添加fileids
        if ([table isEqualToString:ADVERTISING_PICTURE] ||[table isEqualToString:WORK_RECORD] ||[table isEqualToString:WORK_DIARY]||[table isEqualToString:WORK_LOG]||[table isEqualToString:PROCESS_RECORD]||[table isEqualToString:INSPECT_PROCESS_RECORD]||[table isEqualToString:SAMPLE_PROCESS_RECORD] || [table isEqualToString:ADDRESS] || [table isEqualToString:PATROL_RECORD] || [table isEqualToString:SAFE_RECORD_BASIC]){
            [self.attachFileids addObject:ids];
        }
    }
    
    // 工作记录表数据
    if([table isEqualToString:WORK_RECORD])
    {
        NSMutableArray *workRecordArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSMutableDictionary *dic = [self queryWorkRecordForId:ids];
            [workRecordArray addObject:dic];
        }
        NSLog(@"%@", workRecordArray);
        return workRecordArray;
    }
    // 日记表数据
    else if([table isEqualToString:WORK_DIARY])
    {
        NSMutableArray *workDiaryArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSMutableDictionary *dic=[self queryWorkDiaryForId:ids];
            [workDiaryArray addObject:dic];
        }
        return workDiaryArray;
    }
    
    // 日志表数据
    else if([table isEqualToString:WORK_LOG]){
        NSMutableArray *workLogArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSMutableDictionary *logDic=[self queryWorkLogForId:ids];
            [workLogArray addObject:logDic];
        }
        return workLogArray;
    }
    // 巡检流程表
    else if([table isEqualToString:INSPECT_PROCESS]){
        NSMutableArray *inspectProcessArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSMutableDictionary *dic=[self queryInspectProcessForId:ids];
            [inspectProcessArray addObject:dic];
        }
        return inspectProcessArray;
    }
    // 巡检流程记录表
    else if([table isEqualToString:INSPECT_PROCESS_RECORD]){
        NSMutableArray *inspectProcessRecordArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSMutableDictionary *dic=[self queryInspectProcessRecordForId:ids];
            [inspectProcessRecordArray addObject:dic];
        }
        return inspectProcessRecordArray;
    }
    // 用户巡检项表
    else if ([table isEqualToString:INSPECT_USER_ITEM]){
        NSMutableArray *inspectUserItemArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSMutableDictionary *dic=[self queryInspectUserItemForId:ids];
            [inspectUserItemArray addObject:dic];
        }
        return inspectUserItemArray;
    }
    // 一键汇总表
    else if([table isEqualToString:INSPECT_TOTAL_RECORD]){
        
        NSMutableArray *inspectTotalArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSMutableDictionary *dic=[self queryInspectTotalRecordForId:ids];
            [inspectTotalArray addObject:dic];
        }
        return inspectTotalArray;
    }
    // 流程表
    else if([table isEqualToString:PROCESS]){
        NSMutableArray *processArray=[NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic=[self queryProcessForId:ids];
            [processArray addObject:dic];
        }
        return processArray;
     
    // 巡视表
    } else if ([table isEqualToString:PATROL_RECORD]) {
        NSMutableArray *partrolArray = [NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic=[self queryPatrolForId:ids];
            [partrolArray addObject:dic];
        }
        return partrolArray;
    
    // 安全基本信息表
    } else if ([table isEqualToString:SAFE_RECORD_BASIC]) {
        NSMutableArray *safeBaseArray = [NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic = [self querySafeBasicForId:ids];
            [safeBaseArray addObject:dic];
        }
        return safeBaseArray;
     
    // 安全施工三类人员表
    } else if ([table isEqualToString:SAFE_CONSTRUCT]) {
        NSMutableArray *safeConstructArray = [NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic = [self querySafeConstructForId:ids];
            [safeConstructArray addObject:dic];
        }
        return safeConstructArray;
      
    // 特种作业人员
    } else if ([table isEqualToString:SAFE_SPECIAL_TYPE]) {
        NSMutableArray *safeSpecialTypeArray = [NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic = [self querySafeSpecialTypeForId:ids];
            [safeSpecialTypeArray addObject:dic];
        }
        return safeSpecialTypeArray;
        
    // 监理安全巡查
    } else if ([table isEqualToString:SECURITY_PATROL]) {
        NSMutableArray *safeSecurityPatrolArray = [NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic = [self querySecurityPatrolForId:ids];
            [safeSecurityPatrolArray addObject:dic];
        }
        return safeSecurityPatrolArray;
        
    // 危险性较大工程监理检查
    } else if ([table isEqualToString:SAFE_DANGER]) {
        NSMutableArray *safeDangerArray = [NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic = [self querySafeDangerForId:ids];
            [safeDangerArray addObject:dic];
        }
        return safeDangerArray;
        
    // 施工设备进场
    } else if ([table isEqualToString:SAFE_CONSTRUCT_DEVICE]) {
        NSMutableArray *safeDeviceArray = [NSMutableArray array];
        for (NSString *ids in idArray) {
            NSDictionary *dic = [self querySafeDeviceForId:ids];
            [safeDeviceArray addObject:dic];
        }
        return safeDeviceArray;
        
    } else {
        return idArray;
    }
}

#pragma mark - 查询本地记录表数据
- (NSMutableDictionary *)queryWorkRecordForId:(NSString *)recordId {
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT * FROM WORK_RECORD WHERE ID = '%@'",recordId];
    FMResultSet *resule=[self.db executeQuery:sqlStr];
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"ID"] forKey:@"id"];
        [dic setObject:[resule stringForColumn:@"PRO_ID"] forKey:@"proId"];
        
        [dic setObject:DEFISNUL([resule stringForColumn:@"PRO_NAME"]) forKey:@"projectName"];
        [dic setObject:[resule stringForColumn:@"RECORD_USER"] forKey:@"recordUser"];
        [dic setObject:[resule stringForColumn:@"RECORD_MASTER"] forKey:@"recordMaster"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RECORD_SUPERVISION_USER"]) forKey:@"recordSupervisionUsers"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"WEATHER"]) forKey:@"weather"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"ADDRESS_ID"]) forKey:@"addId"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"ADDRES_INFO"]) forKey:@"addInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RECORD_TYPE"]) forKey:@"recordType"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RECORD_TITLE"]) forKey:@"recordTitle"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RECORD_NUMBER"]) forKey:@"recordNumber"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RECORD_FILE_PATH"]) forKey:@"recordFilepath"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RECORD_INFO"]) forKey:@"recordInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RECORDONTENT"]) forKey:@"recordContent"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"STATE"]) forKey:@"state"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SUPERVISOR_PRO_UNIT_ID"]) forKey:@"supervisorProUnitId"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"CONSTRUCT_PRO_UNIT_ID"]) forKey:@"constructProUnitId"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SUPERVISOR_PRO_UNIT_NAME"]) forKey:@"supervisorProUnitName"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"CONSTRUCT_PRO_UNIT_NAME"]) forKey:@"constructProUnitName"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SUPERVISOR_CONTRACT_NUMBER"]) forKey:@"supervisorContractNumber"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"CONSTRUCT_CONTRACT_NUMBER"]) forKey:@"constructContractNumber"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SIDE_START_TIME"]) forKey:@"sideStartTime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SIDE_END_TIME"]) forKey:@"sideEndTime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SITE_NAME"]) forKey:@"siteName"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"RANGE_AND_POSITION"]) forKey:@"rangeAndPosition"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"EXTEND_INFO"]) forKey:@"extendInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"CREATE_TIME"]) forKey:@"createtime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"CREATE_USER_NAME"]) forKey:@"createusername"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_TIME"]) forKey:@"modifytime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_USER_NAME"] )forKey:@"modifyusername"];
    }
    return dic;
}

#pragma mark - 查询本地日记表数据
- (NSMutableDictionary *)queryWorkDiaryForId:(NSString *)recordId {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString * sqlStr=[NSString stringWithFormat:@"SELECT * FROM WORK_DIARY WHERE ID='%@'",recordId];
    FMResultSet * resule=[self.db executeQuery:sqlStr];
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"ID"] forKey:@"id"];
        [dic setObject:[resule stringForColumn:@"PRO_ID"] forKey:@"proId"];
        [dic setObject:[resule stringForColumn:@"DIARY_USER"] forKey:@"diaryUser"];
        [dic setObject:[resule stringForColumn:@"DIARY_TYPE"] forKey:@"diaryType"];
        [dic setObject:[resule stringForColumn:@"DIARY_TIME"] forKey:@"diaryTime"];
        [dic setObject:[resule stringForColumn:@"REVIEW_TIME"] forKey:@"reviewTime"];
        [dic setObject:[resule stringForColumn:@"TOUR_INFO"] forKey:@"tourInfo"];
        [dic setObject:[resule stringForColumn:@"CHECK_INFO"] forKey:@"checkInfo"];
        [dic setObject:[resule stringForColumn:@"SAFE_INFO"] forKey:@"safeInfo"];
        [dic setObject:[resule stringForColumn:@"SITE_INFO"] forKey:@"siteInfo"];
        [dic setObject:[resule stringForColumn:@"SUPERVISE_INFO"] forKey:@"superviseInfo"];
        [dic setObject:[resule stringForColumn:@"FOLLOW_INFO"] forKey:@"followInfo"];
        [dic setObject:[resule stringForColumn:@"OTHER_INFO"] forKey:@"otherInfo"];
        [dic setObject:[resule stringForColumn:@"ENTER_EXTER_COMM_INFO"] forKey:@"enterExterCommuInfo"];
        [dic setObject:[resule stringForColumn:@"MEETING_INFO"] forKey:@"meetingInfo"];
        [dic setObject:[resule stringForColumn:@"REVIEW_INFO"] forKey:@"reviewInfo"];
        [dic setObject:[resule stringForColumn:@"REVIEW_SCORE"] forKey:@"reviewScore"];
        [dic setObject:[resule stringForColumn:@"REVIEW_USER"] forKey:@"reviewUsers"];
        [dic setObject:[resule stringForColumn:@"REVIEW_STATE"] forKey:@"reviewState"];
        [dic setObject:[resule stringForColumn:@"WEATHER"] forKey:@"weather"];
        [dic setObject:[resule stringForColumn:@"FILEIDS"] forKey:@"fileids"];
        [dic setObject:[resule stringForColumn:@"DIARY_DESC"] forKey:@"diaryDesc"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_TIME"]) forKey:@"modifytime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_USER_NAME"]) forKey:@"modifyusername"];
        [dic setObject:[resule stringForColumn:@"CREATE_TIME"] forKey:@"createtime"];
        [dic setObject:[resule stringForColumn:@"CREATE_USER_NAME"] forKey:@"createusername"];
        
        // 迭代新增字段
        [dic setObject:DEFISNUL([resule stringForColumn:@"JIANCHA_INFO"]) forKey:@"jianchaInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"ZHILIANG_INFO"]) forKey:@"zhiliangInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"JINDU_INFO"]) forKey:@"jinduInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"CAILIAO_INFO"]) forKey:@"cailiaoInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"YINBI_INFO"]) forKey:@"yinbiInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SHOUFAWEN_INFO"]) forKey:@"shoufawenInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"JIANZHENG_INFO"]) forKey:@"jianzhengInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"HUIYI_INFO"]) forKey:@"huiyiInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"PATROL_RECORD_INFO"]) forKey:@"patrolRecordInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SAFE_RECORD_INFO"]) forKey:@"safeRecordInfo"];
    }
    return dic;
}

#pragma mark - 查询本地日志表数据，上传到服务器。(审核操作)
- (NSMutableDictionary *)queryWorkLogForId:(NSString *) recordId {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString * sqlStr=[NSString stringWithFormat:@"SELECT * FROM WORK_LOG WHERE ID='%@'",recordId];
    FMResultSet * resule=[self.db executeQuery:sqlStr];
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"ID"] forKey:@"id"];
        [dic setObject:[resule stringForColumn:@"PRO_ID"] forKey:@"proId"];
        [dic setObject:[resule stringForColumn:@"LOG_TYPE"] forKey:@"logType"];
        [dic setObject:[resule stringForColumn:@"LOG_USERS"] forKey:@"logUsers"];
        [dic setObject:[resule stringForColumn:@"REVIEW_TIME"] forKey:@"reviewTime"];
        [dic setObject:[resule stringForColumn:@"CONSTRACT_PROGRESS_INFO"] forKey:@"constractProgressInfo"];
        [dic setObject:[resule stringForColumn:@"DAY_SUPERVISION_WORK_INFO"] forKey:@"daySupervisionWorkInfo"];
        [dic setObject:[resule stringForColumn:@"OTHER_SUPERVISION_INFO"] forKey:@"otherSupervisionInfo"];
        [dic setObject:[resule stringForColumn:@"SAFE_PATROL_INFO"] forKey:@"safePatrolInfo"];
        [dic setObject:[resule stringForColumn:@"SAFE_FILE_REVIEW_INFO"] forKey:@"safeFileReviewInfo"];
        [dic setObject:[resule stringForColumn:@"SAFE_MEETING_INFO"] forKey:@"safeMeetingInfo"];
        [dic setObject:[resule stringForColumn:@"PROBLEM_DEAL_INFO"] forKey:@"problemDealInfo"];
        [dic setObject:[resule stringForColumn:@"REVIEW_INFO"] forKey:@"reviewInfo"];
        [dic setObject:[resule stringForColumn:@"REVIEW_SCORE"] forKey:@"reviewScore"];
        [dic setObject:[resule stringForColumn:@"REVIEW_USERS"] forKey:@"reviewUsers"];
        [dic setObject:[resule stringForColumn:@"REVIEW_STATE"] forKey:@"reviewState"];
        [dic setObject:[resule stringForColumn:@"FILEIDS"] forKey:@"fileids"];
        [dic setObject:[resule stringForColumn:@"LOG_DESC"] forKey:@"logDesc"];
        [dic setObject:[resule stringForColumn:@"MODIFY_TIME"] forKey:@"modifytime"];
        [dic setObject:[resule stringForColumn:@"MODIFY_USER_NAME"] forKey:@"modifyusername"];
        [dic setObject:[resule stringForColumn:@"MODIFY_IP"] forKey:@"modifyip"];
        //创建时间
        [dic setObject:[resule stringForColumn:@"CREATE_TIME"] forKey:@"createtime"];
        [dic setObject:[resule stringForColumn:@"CREATE_USER_NAME"] forKey:@"createusername"];
        //迭代新增字段
        [dic setObject:DEFISNUL([resule stringForColumn:@"JIANCHA_INFO"]) forKey:@"jianchaInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"ZHILIANG_INFO"]) forKey:@"zhiliangInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"JINDU_INFO"]) forKey:@"jinduInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"CAILIAO_INFO"]) forKey:@"cailiaoInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"YINBI_INFO"]) forKey:@"yinbiInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SHOUFAWEN_INFO"]) forKey:@"shoufawenInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"JIANZHENG_INFO"]) forKey:@"jianzhengInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"HUIYI_INFO"]) forKey:@"huiyiInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"PATROL_RECORD_INFO"]) forKey:@"patrolRecordInfo"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SAFE_RECORD_INFO"]) forKey:@"safeRecordInfo"];
    }
    return dic;
}

#pragma mark - 查询本地巡检流程表数据
- (NSMutableDictionary *)queryInspectProcessForId:(NSString *)Id {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString * sqlStr=[NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS WHERE ID='%@'",Id];
    FMResultSet * resule=[self.db executeQuery:sqlStr];
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"ID"] forKey:@"id"];
        [dic setObject:[resule stringForColumn:@"PRO_ID"] forKey:@"proId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_GROUP_ID"] forKey:@"inspectGroupId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_NAME"] forKey:@"inspectName"];
        [dic setObject:[resule stringForColumn:@"INSPECT_START_TIME"] forKey:@"inspectStartTime"];
        [dic setObject:[resule stringForColumn:@"INSPECT_END_TIME"] forKey:@"inspectEndTime"];
        [dic setObject:[resule stringForColumn:@"INSPECT_PUBLISHER"] forKey:@"inspectPublisher"];
        [dic setObject:[resule stringForColumn:@"INSPECT_RECTIFICATE_LEADER"] forKey:@"inspectRectificateLeader"];
        [dic setObject:[resule stringForColumn:@"INSPECT_GROUP_LEADER"] forKey:@"inspectGroupLeader"];
        [dic setObject:[resule stringForColumn:@"INSPECT_STATE"] forKey:@"inspectState"];
        [dic setObject:[resule stringForColumn:@"INSPECT_DESC"] forKey:@"inspectDesc"];
        [dic setObject:[resule stringForColumn:@"INSPECT_TOTAL_DESC"] forKey:@"inspectTotalDesc"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_TIME"]) forKey:@"modifytime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_USER_NAME"]) forKey:@"modifyusername"];
        [dic setObject:[resule stringForColumn:@"CREATE_TIME"] forKey:@"createtime"];
        [dic setObject:[resule stringForColumn:@"CREATE_USER_NAME"] forKey:@"createusername"];
    }
    return dic;
}

#pragma mark - 查询本地巡检流程记录表数据
-(NSMutableDictionary *)queryInspectProcessRecordForId:(NSString *)Id {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString * sqlStr=[NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS_RECORD WHERE ID='%@'",Id];
    FMResultSet * resule=[self.db executeQuery:sqlStr];
    
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"ID"] forKey:@"id"];
        [dic setObject:[resule stringForColumn:@"INSPECT_PROCESS_ID"] forKey:@"inspectProcessId"];
        [dic setObject:[resule stringForColumn:@"PRO_ID"] forKey:@"proId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_USER_ID"] forKey:@"inspectUserId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_ITEM_ID"] forKey:@"inspectItemId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_ITEM_STATE"] forKey:@"inspectItemState"];
        [dic setObject:[resule stringForColumn:@"INSPECT_INFO"] forKey:@"inspectInfo"];
        [dic setObject:[resule stringForColumn:@"INSPECT_USER_ITEM_ID"] forKey:@"inspectUserItemId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_DESC"] forKey:@"inspectDesc"];
        [dic setObject:[resule stringForColumn:@"INSPECT_RESULT"] forKey:@"inspectResult"];
        [dic setObject:[resule stringForColumn:@"INSPECT_SCORE"] forKey:@"inspectScore"];
        [dic setObject:[resule stringForColumn:@"INSPECT_ITEM_RECIFICATE_LEADER"] forKey:@"inspectItemRecificateLeader"];
        [dic setObject:[resule stringForColumn:@"INSPECT_RECIFICATE_DESC"] forKey:@"inspectRecificateDesc"];
        [dic setObject:[resule stringForColumn:@"INSPECT_RECIFICATE_REVIEW_USER"] forKey:@"inspectRecificateReviewUser"];
        [dic setObject:[resule stringForColumn:@"INSPECT_RECIFICATE_REVIRE_SCORE"] forKey:@"inspectRecificateRevireScore"];
        [dic setObject:[resule stringForColumn:@"INSPECT_RECIFICATE_REVIEW"] forKey:@"inspectRecificateReview"];
        [dic setObject:[resule stringForColumn:@"INSPECT_DO_TIME"] forKey:@"inspectDoTime"];
        [dic setObject:[resule stringForColumn:@"CREATE_TIME"] forKey:@"createtime"];
        [dic setObject:[resule stringForColumn:@"CREATE_USER_NAME"] forKey:@"createusername"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_TIME"]) forKey:@"modifytime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_USER_NAME"]) forKey:@"modifyusername"];
    }
    return dic;
}

#pragma mark - 查询本地用户巡检项表数据
- (NSMutableDictionary *)queryInspectUserItemForId:(NSString *)Id {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString * sqlStr=[NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE ID='%@'",Id];
    FMResultSet * resule=[self.db executeQuery:sqlStr];
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"ID"] forKey:@"id"];
        [dic setObject:[resule stringForColumn:@"INSPECT_PROCESS_ID"] forKey:@"inspectProcessId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_GROUP_ID"] forKey:@"inspectGroupId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_USER_ID"] forKey:@"inspectUserId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_USER_TYPE"] forKey:@"inspectUserType"];
        [dic setObject:[resule stringForColumn:@"INSPECT_USER_DESC"] forKey:@"inspectUserDesc"];
        [dic setObject:[resule stringForColumn:@"INSPECT_ITEM_ID"] forKey:@"inspectItemId"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"SUPER_PROCESS_ID"] ) forKey:@"superProcessId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_CURRENT_STATE"] forKey:@"inspectCurrentState"];
        [dic setObject:[resule stringForColumn:@"INSPECT_ADDTIONAL_NAME"] forKey:@"inspectAddtionalName"];
        [dic setObject:[resule stringForColumn:@"INSPECT_DESC"] forKey:@"inspectDesc"];
        [dic setObject:[resule stringForColumn:@"CREATE_TIME"] forKey:@"createtime"];
        [dic setObject:[resule stringForColumn:@"CREATE_USER_NAME"] forKey:@"createusername"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_TIME"]) forKey:@"modifytime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_USER_NAME"]) forKey:@"modifyusername"];
    }
    return dic;
}

#pragma mark - 查询本地一键汇总
- (NSMutableDictionary *)queryInspectTotalRecordForId:(NSString *)Id {
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString * sqlStr=[NSString stringWithFormat:@"SELECT * FROM INSPECT_TOTAL_RECORD WHERE ID='%@'",Id];
    FMResultSet * resule=[self.db executeQuery:sqlStr];
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"ID"] forKey:@"id"];
        [dic setObject:[resule stringForColumn:@"INSPECT_PROCESS_ID"] forKey:@"inspectProcessId"];
        [dic setObject:[resule stringForColumn:@"INSPECT_TOTAL_TIME"] forKey:@"inspectTotalTime"];
        [dic setObject:[resule stringForColumn:@"INSPECT_TOTAL_INFO"] forKey:@"inspectTotalInfo"];
        [dic setObject:[resule stringForColumn:@"INSPECT_TOTAL_DESC"] forKey:@"inspectTotalDesc"];
        [dic setObject:[resule stringForColumn:@"INSPECT_TOTAL_USER"] forKey:@"inspectTotalUser"];
        [dic setObject:[resule stringForColumn:@"EXTEND_INFO"] forKey:@"extendInfo"];
        [dic setObject:[resule stringForColumn:@"CREATE_TIME"] forKey:@"createtime"];
        [dic setObject:[resule stringForColumn:@"CREATE_USER_NAME"] forKey:@"createusername"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_TIME"]) forKey:@"modifytime"];
        [dic setObject:DEFISNUL([resule stringForColumn:@"MODIFY_USER_NAME"]) forKey:@"modifyusername"];
    }
    return dic;
}

#pragma mark - 查询流程表数据
- (NSDictionary *)queryProcessForId:(NSString *)ids{
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"addressId":[result stringForColumn:@"ADDRESS_ID"],
                       @"processType":[NSString stringWithFormat:@"%d", [result intForColumn:@"PROCESS_TYPE"]],
                       @"processStage":[NSString stringWithFormat:@"%d", [result intForColumn:@"PROCESS_STAGE"]],
                       @"processPublishers":[result stringForColumn:@"PROCESS_PUBLISHERS"],
                       @"processMasters":[result stringForColumn:@"PROCESS_MASTERS"],
                       @"processRecifyUsers":[result stringForColumn:@"PROCESS_RECIFY_USERS"],
                       @"processRecifyUnits":[result stringForColumn:@"PROCESS_RECIFY_UNITS"],
                       @"recifyReviewUsers":[result stringForColumn:@"RECIFY_REVIEW_USERS"],
                       @"beginTime":[result stringForColumn:@"BEGIN_TIME"],
                       @"requiredEndtime":[result stringForColumn:@"REQUIRED_END_TIME"],
                       @"endTime":[result stringForColumn:@"END_TIME"],
                       @"processTitle":[result stringForColumn:@"PROCESS_TITLE"],
                       @"processNumber":[result stringForColumn:@"PROCESS_NUMBER"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"],
                       @"addressInfo":[result stringForColumn:@"ADDRES_INFO"]

                       };
    }
    [db close];
    return pragameDic;
}

#pragma mark - 查询巡视数据
- (NSDictionary *)queryPatrolForId:(NSString *)ids {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM PATROL_RECORD WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"supervisorProUnitId":[result stringForColumn:@"SUPERVISOR_PRO_UNIT_ID"],
                       @"constructProUnitId":[result stringForColumn:@"CONSTRUCT_PRO_UNIT_ID"],
                       @"supervisorProUnitName":[result stringForColumn:@"SUPERVISOR_PRO_UNIT_NAME"],
                       @"constructProUnitName":[result stringForColumn:@"CONSTRUCT_PRO_UNIT_NAME"],
                       @"supervisorContractNumber":[result stringForColumn:@"SUPERVISOR_CONTRACT_NUMBER"],
                       @"constructContractNumber":[result stringForColumn:@"CONSTRUCT_CONTRACT_NUMBER"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordType":[result stringForColumn:@"RECORD_TYPE"],
                       @"recordTitle":[result stringForColumn:@"RECORD_TITLE"],
                       @"recordContent":[result stringForColumn:@"RECORD_CONTENT"],
                       @"state":[result stringForColumn:@"STATE"],
                       @"recordNumber":[result stringForColumn:@"RECORD_NUMBER"],
                       @"startTime":[result stringForColumn:@"START_TIME"],
                       @"endTime":[result stringForColumn:@"END_TIME"],
                       @"startAndEndTime":[result stringForColumn:@"START_AND_END_TIME"],
                       @"weather":[result stringForColumn:@"WEATHER"],
                       @"addId":[result stringForColumn:@"ADD_ID"],
                       @"addInfo":[result stringForColumn:@"ADD_INFO"],
                       @"rangeAndPosition":[result stringForColumn:@"RANGE_AND_POSITION"],
                       @"majorproAndPerson":[result stringForColumn:@"MAJORPRO_AND_PERSON"],
                       @"majorInspectData":[result stringForColumn:@"MAJOR_INSPECT_DATA"],
                       @"problemAndDeal":[result stringForColumn:@"PROBLEM_AND_DEAL"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"]
                       };
    }
    [db close];
    return pragameDic;
}

#pragma mark - 查询安全基本数据
- (NSDictionary *)querySafeBasicForId:(NSString *)ids {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAFE_RECORD_BASIC WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"supervisorProUnitId":[result stringForColumn:@"SUPERVISOR_PRO_UNIT_ID"],
                       @"constructProUnitId":[result stringForColumn:@"CONSTRUCT_PRO_UNIT_ID"],
                       @"supervisorProUnitName":[result stringForColumn:@"SUPERVISOR_PRO_UNIT_NAME"],
                       @"constructProUnitName":[result stringForColumn:@"CONSTRUCT_PRO_UNIT_NAME"],
                       @"supervisorContractNumber":[result stringForColumn:@"SUPERVISOR_CONTRACT_NUMBER"],
                       @"constructContractNumber":[result stringForColumn:@"CONSTRUCT_CONTRACT_NUMBER"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordType":[result stringForColumn:@"RECORD_TYPE"],
                       @"recordTitle":[result stringForColumn:@"RECORD_TITLE"],
                       @"recordContent":[result stringForColumn:@"RECORD_CONTENT"],
                       @"state":[result stringForColumn:@"STATE"],
                       @"recordNumber":[result stringForColumn:@"RECORD_NUMBER"],
                       @"supervisorOpinion":[result stringForColumn:@"SUPERVISOR_OPINION"],
                       @"chiefSupervisorOpinion":[result stringForColumn:@"CHIEF_SUPERVISOR_OPINION"],
                       @"chiefSupervisorOpinionState":[result stringForColumn:@"CHIEF_SUPERVISOR_OPINION_STATE"],
                       @"problemAndDeal":[result stringForColumn:@"PROBLEM_AND_DEAL"],
                       @"projectContent":[result stringForColumn:@"PROJECT_CONTENT"],
                       @"otherInfo":[result stringForColumn:@"OTHER_INFO"],
                       @"weather":[result stringForColumn:@"WEATHER"],
                       @"addId":[result stringForColumn:@"ADD_ID"],
                       @"addInfo":[result stringForColumn:@"ADD_INFO"],
                       @"constructContractMoney":[result stringForColumn:@"CONSTRUCT_CONTRACT_MONEY"],
                       @"recifyState":[result stringForColumn:@"RECIFY_STATE"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"]
                       };
    }
    [db close];
    return pragameDic;
}

#pragma mark - 查询安全施工三类人员表
- (NSDictionary *)querySafeConstructForId:(NSString *)ids {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAFE_CONSTRUCT WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"basicRecordId":[result stringForColumn:@"BASIC_RECORD_ID"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordType":[result stringForColumn:@"RECORD_TYPE"],
                       @"recordTitle":[result stringForColumn:@"RECORD_TITLE"],
                       @"recordNumber":[result stringForColumn:@"RECORD_NUMBER"],
                       @"totalUserType":[result stringForColumn:@"TOTAL_USER_TYPE"],
                       @"dangerFactor":[result stringForColumn:@"DANGER_FACTOR"],
                       @"userTitle":[result stringForColumn:@"USER_TITLE"],
                       @"isOnPosition":[result stringForColumn:@"IS_ON_POSITION"],
                       @"isDoCheck":[result stringForColumn:@"IS_DO_CHECK"],
                       @"isEffecitive":[result stringForColumn:@"IS_EFFECITIVE"],
                       @"isMeetRequire":[result stringForColumn:@"IS_MEET_REQUIRE"],
                       @"otherNote":[result stringForColumn:@"OTHER_NOTE"],
                       @"proOnDutyCnt":[result stringForColumn:@"PRO_ON_DUTY_CNT"],
                       @"proFitCnt":[result stringForColumn:@"PRO_FIT_CNT"],
                       @"proFitRate":[result stringForColumn:@"PRO_FIT_RATE"],
                       @"proIsMeetRequire":[result stringForColumn:@"PRO_IS_MEET_REQUIRE"],
                       @"safeOnDutyCnt":[result stringForColumn:@"SAFE_ONDUTYCNT"],
                       @"safeFitCnt":[result stringForColumn:@"SAFE_FIT_CNT"],
                       @"safeFitRate":[result stringForColumn:@"SAFE_FIT_RATE"],
                       @"safeIsMeetRequire":[result stringForColumn:@"SAFE_IS_MEET_REQUIRE"],
                       @"username":[result stringForColumn:@"USERNAME"],
                       @"realname":[result stringForColumn:@"REALNAME"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"]
                       };
    }
    [db close];
    return pragameDic;
}

#pragma mark - 查询安全特种作业表
- (NSDictionary *)querySafeSpecialTypeForId:(NSString *)ids {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAFE_SPECIAL_TYPE WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"basicRecordId":[result stringForColumn:@"BASIC_RECORD_ID"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordType":[result stringForColumn:@"RECORD_TYPE"],
                       @"recordTitle":[result stringForColumn:@"RECORD_TITLE"],
                       @"recordNumber":[result stringForColumn:@"RECORD_NUMBER"],
                       @"checkName":[result stringForColumn:@"CHECK_NAME"],
                       @"workType":[result stringForColumn:@"WORK_TYPE"],
                       @"applyCnt":[result stringForColumn:@"APPLY_CNT"],
                       @"checkRealCnt":[result stringForColumn:@"CHECK_REAL_CNT"],
                       @"effectiveCnt":[result stringForColumn:@"EFFECTIVE_CNT"],
                       @"inEffectiveCnt":[result stringForColumn:@"IN_EFFECTIVE_CNT"],
                       @"fitRate":[result stringForColumn:@"FIT_RATE"],
                       @"checkOpinion":[result stringForColumn:@"CHECK_OPINION"],
                       @"souceCheckCnt":[result stringForColumn:@"SOUCE_CHECK_CNT"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"]
                       };
    }
    [db close];
    return pragameDic;
}


#pragma mark - 查询监理安全巡查表
- (NSDictionary *)querySecurityPatrolForId:(NSString *)ids {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAFE_SECURITY_PATROL WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"basicRecordId":[result stringForColumn:@"BASIC_RECORD_ID"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordType":[result stringForColumn:@"RECORD_TYPE"],
                       @"recordTitle":[result stringForColumn:@"RECORD_TITLE"],
                       @"recordNumber":[result stringForColumn:@"RECORD_NUMBER"],
                       @"dangerFactor":[result stringForColumn:@"DANGER_FACTOR"],
                       @"dealOpinion":[result stringForColumn:@"DEAL_OPINION"],
                       @"constructResponsiblePersonUserId":[result stringForColumn:@"CONSTRUCT_RESPONSIBLE_PERSON_USER_ID"],
                       @"constructResponsiblePersonRealname":[result stringForColumn:@"CONSTRUCT_RESPONSIBLE_PERSON_REALNAME"],
                       @"reviewTime":[result stringForColumn:@"REVIEW_TIME"],
                       @"recifyAndReformInfo":[result stringForColumn:@"RECIFY_AND_REFORM_INFO"],
                       @"reviewOpinion":[result stringForColumn:@"REVIEW_OPINION"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"]
                       };
    }
    [db close];
    return pragameDic;
}


#pragma mark - 危险性较大工程监理检查
- (NSDictionary *)querySafeDangerForId:(NSString *)ids {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAFE_DANGER WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"basicRecordId":[result stringForColumn:@"BASIC_RECORD_ID"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordType":[result stringForColumn:@"RECORD_TYPE"],
                       @"recordTitle":[result stringForColumn:@"RECORD_TITLE"],
                       @"recordNumber":[result stringForColumn:@"RECORD_NUMBER"],
                       @"checkName":[result stringForColumn:@"CHECK_NAME"],
                       @"checkType":[result stringForColumn:@"CHECK_TYPE"],
                       @"checkInfo":[result stringForColumn:@"CHECK_INFO"],
                       @"isOnPosition":[result stringForColumn:@"IS_ON_POSITION"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"]
                       };
    }
    [db close];
    return pragameDic;
}


#pragma mark - 施工设备进场
- (NSDictionary *)querySafeDeviceForId:(NSString *)ids {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAFE_CONSTRUCT_DEVICE WHERE ID = '%@'",ids];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSDictionary *pragameDic = [NSDictionary dictionary];
    while ([result next]) {
        pragameDic = @{
                       @"id":[result stringForColumn:@"ID"],
                       @"proId":[result stringForColumn:@"PRO_ID"],
                       @"basicRecordId":[result stringForColumn:@"BASIC_RECORD_ID"],
                       @"recordUser":[result stringForColumn:@"RECORD_USER"],
                       @"recordType":[result stringForColumn:@"RECORD_TYPE"],
                       @"recordTitle":[result stringForColumn:@"RECORD_TITLE"],
                       @"recordNumber":[result stringForColumn:@"RECORD_NUMBER"],
                       @"diviceName":[result stringForColumn:@"DIVICE_NAME"],
                       @"workType":[result stringForColumn:@"WORK_TYPE"],
                       @"userAddr":[result stringForColumn:@"USER_ADDR"],
                       @"isMeetQulification":[result stringForColumn:@"IS_MEET_QULIFICATION"],
                       @"isMeetStandard":[result stringForColumn:@"IS_MEET_STANDARD"],
                       @"inRegister":[result stringForColumn:@"IN_REGISTER"],
                       @"isAgree":[result stringForColumn:@"IS_AGREE"],
                       @"extendInfo":[result stringForColumn:@"EXTEND_INFO"],
                       @"createip":[result stringForColumn:@"CREATE_IP"],
                       @"createtime":[result stringForColumn:@"CREATE_TIME"],
                       @"createusername":[result stringForColumn:@"CREATE_USER_NAME"],
                       @"modifyip":[result stringForColumn:@"MODIFY_IP"],
                       @"modifytime":[result stringForColumn:@"MODIFY_TIME"],
                       @"modifyusername":[result stringForColumn:@"MODIFY_USER_NAME"]
                       };
    }
    [db close];
    return pragameDic;
}


#pragma mark - 公共方法集

// 修改表数据状态为已上传
- (void)updateStateForTable:(NSString *)table andId:(NSString *)id {
    DBHelper *helper=[DBHelper help];
    [helper DataBase:self.db updateTable:table setKeyValues:@{@"LOCAL_MODIFY_STATE":@""} whereCondition:@{@"ID":id}];
}

#pragma mark - 获取本地数据ID和最后修改时间(jsonStr)
- (NSString *)getLocalIDAndModifyTimeFrom:(NSString *)table {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT ID, MODIFY_TIME, LOCAL_MODIFY_STATE FROM %@ WHERE LOCAL_MODIFY_STATE NOT IN ('ADD', 'MOD', 'other')", table];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    while ([result next]) {
        NSString *ID = [result stringForColumn:@"ID"];
        if (!ID) {
            continue;
        }
        NSString *localType = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
        NSString *modifyTime = DEFISNUL([result stringForColumn:@"MODIFY_TIME"]);
        
        if ([table isEqualToString:ADVERTISING_PICTURE] || [table isEqualToString:WORK_RECORD] || [table isEqualToString:WORK_DIARY] || [table isEqualToString:WORK_LOG] || [table isEqualToString:PROCESS_RECORD] || [table isEqualToString:INSPECT_PROCESS_RECORD] || [table isEqualToString:SAMPLE_PROCESS_RECORD] || [table isEqualToString:ADDRESS] || [table isEqualToString:PATROL_RECORD] || [table isEqualToString:SAFE_RECORD_BASIC]){
            [self.attachFileids addObject:ID];
            //            if([table isEqualToString:PROCESS_RECORD]){
            //                NSLog(@"本地流程记录id：%@",ID);
            //            }
        }
        
        // 要删除的数据
        if([localType isEqualToString:@"DEL"]){
            NSDictionary *pragameDic = @{@"id":ID, @"modifyTime":modifyTime,@"syncState":@"-2"};
            [array addObject:pragameDic];
            
        }else{
            NSDictionary *pragameDic = @{@"id":ID, @"modifyTime":modifyTime};
            [array addObject:pragameDic];
        }
    }
    [db close];
    NSString *jsonStr = [LSUtility dictionaryToJson_4:array];
    return jsonStr;
}

#pragma mark - 条件获取本地ID和最后修改时间
- (NSString *)checkLocalIDAndModifyTimeFrom:(NSString *)tableName where:(NSString *)condition equal:(NSString *)equal {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    if (![db open]) {
        [db open];
    }
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT ID, MODIFY_TIME FROM %@ WHERE %@ = '%@' AND LOCAL_MODIFY_STATE NOT IN('ADD','MOD')", tableName, condition, equal];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    if (![result next]) {
        NSDictionary *pragameDic = @{@"id":@"", @"modifyTime":@""};
        [array addObject:pragameDic];
    } else {
        while ([result next]) {
            NSString *ID = [result stringForColumn:@"ID"];
            if ([ID isEqualToString:@""]) {
                continue;
            }
            NSString *modifyTime = DEFISNUL([result stringForColumn:@"MODIFY_TIME"]);
            NSDictionary *pragameDic = @{@"id":ID, @"modifyTime":modifyTime};
            [array addObject:pragameDic];
            //记录表 日记表 广告表 日志表 流程记录表 巡检路程记录表  见证取样流程记录表 地址表 需要添加fileids
            if([tableName isEqualToString:ADVERTISING_PICTURE] || [tableName isEqualToString:WORK_RECORD] || [tableName isEqualToString:WORK_DIARY] || [tableName isEqualToString:WORK_LOG] || [tableName isEqualToString:PROCESS_RECORD] || [tableName isEqualToString:INSPECT_PROCESS_RECORD] || [tableName isEqualToString:SAMPLE_PROCESS_RECORD] || [tableName isEqualToString:ADDRESS] || [tableName isEqualToString:PATROL_RECORD] || [tableName isEqualToString:SAFE_RECORD_BASIC]){
                [self.attachFileids addObject:ID];
                //  if([tableName isEqualToString:PROCESS_RECORD]){
                ////    NSLog(@"本地流程记录id：%@",ID);
                //   }
            }
        }
    }
    NSString *jsonStr = [LSUtility toJSONData:array];
    [db close];
    return jsonStr;
}

#pragma mark -查询所有表格得到id作为fileids

//查询未同步数据 最后的修改时间
- (NSMutableArray *)getIdAndModifyTimeFromTable:(NSString *)table{
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT ID,MODIFY_TIME,LOCAL_MODIFY_STATE FROM %@ WHERE LOCAL_MODIFY_STATE NOT IN('ADD','MOD')",table];
    FMResultSet *resule=[db executeQuery:sql];
    
    NSMutableArray *idAndModifyTimeArr=[NSMutableArray array];
    while ([resule next]) {
        NSString *localType=[resule stringForColumn:@"LOCAL_MODIFY_STATE"];
        NSString *ids=[resule stringForColumn:@"ID"];
        NSString *modify=[resule stringForColumn:@"MODIFY_TIME"];
        
        //要删除的数据
        if([localType isEqualToString:@"DEL"]){
            NSDictionary *dic=@{@"id":ids,@"modifyTime":DEFISNUL(modify), @"syncState":@"-2"};
            [idAndModifyTimeArr addObject:dic];
            
        }else{
            NSDictionary *dic=@{@"id":ids,@"modifyTime":DEFISNUL(modify)};
            [idAndModifyTimeArr addObject:dic];
        }
        //记录表 日记表 广告表 日志表 流程记录表 巡检路程记录表  见证取样流程记录表 地址表  需要添加fileids
        if([table isEqualToString:ADVERTISING_PICTURE] || [table isEqualToString:WORK_RECORD] || [table isEqualToString:WORK_DIARY] || [table isEqualToString:WORK_LOG] || [table isEqualToString:PROCESS_RECORD] || [table isEqualToString:INSPECT_PROCESS_RECORD] || [table isEqualToString:SAMPLE_PROCESS_RECORD] || [table isEqualToString:ADDRESS] || [table isEqualToString:PATROL_RECORD] || [table isEqualToString:SAFE_RECORD_BASIC]){
            [self.attachFileids addObject:ids];
        }
    }
    [db close];
    if(idAndModifyTimeArr.count>0){
        return idAndModifyTimeArr;
    }
    else{
        return nil;
    }
}

#pragma mark - 获取本地数据库有变更的ID
- (NSArray *)getLocalID:(NSString *)localID fromTable:(NSString *)table {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT DISTINCT %@ FROM %@ WHERE LOCAL_MODIFY_STATE NOT IN('ADD','MOD')", localID, table];
    
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    while ([result next]) {
        NSString *ID = [result stringForColumn:localID];
        [array addObject:ID];
    }
    [db close];
    return array;
}

#pragma mark - 删除本地数据
- (void)deleteLocalData:(NSArray *)deleteIDArr fromTable:(NSString *)table {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    for (NSString *ID in deleteIDArr) {
        NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM %@ WHERE ID = '%@'", table, ID];
        if ([db executeUpdate:sqlStr]) {
            
        } else {
            
        }
    }
    [db close];
}

-(void)dealloc{
    
}
@end

